package com.cykj.pos.service.impl;

import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ayg.openapi.utils.ParameterUtils;
import com.ayg.openapi.utils.RsaUtils;
import com.cykj.common.annotation.DataSource;
import com.cykj.common.config.RuoYiConfig;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.enums.DataSourceType;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.dto.ayg.ApiBaseParam;
import com.cykj.pos.domain.dto.ayg.ApiBaseResult;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.mapper.FeiShunSettlementMapper;
import com.cykj.pos.payment.controller.CallbackController;
import com.cykj.pos.pojo.BatchPayment;
import com.cykj.pos.pojo.BatchPaymentList;
import com.cykj.pos.profit.dto.ShareDetailDTO;
import com.cykj.pos.profit.dto.WalletDTO;
import com.cykj.pos.service.*;
import com.cykj.pos.util.*;
import com.cykj.pos.websocket.server.WebSocketServer;
import com.google.gson.Gson;
import com.sec.sdk.SecClient;
import com.sec.sdk.bean.BaseResponse;
import com.sec.sdk.bean.RemitBatchRequestDTO;
import com.sec.sdk.bean.RemitDetailRequestDTO;
import com.sec.sdk.constants.SecGatewayConstants;
import com.sec.sdk.exception.SecGatewayException;
import com.sec.sdk.utils.JsonUtils;
import com.sec.sdk.utils.SecSignature;
import lombok.SneakyThrows;
import okhttp3.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import com.cykj.pos.mapper.BizWalletMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 我的钱包Service业务层处理
 *
 * @author weijianbo
 * @date 2021-01-27
 */
@Service
public class BizWalletServiceImpl extends ServiceImpl<BizWalletMapper, BizWallet> implements IBizWalletService {

    private Logger logger = LoggerFactory.getLogger(CallbackController.class);
    @Autowired
    private IBizMerchantReceiverService iBizMerchantReceiverService;
    @Autowired
    private BizPosMachineMapper posMachineMapper;
    @Autowired
    private IBizWalletService walletService;

    @Autowired
    private IBizMicroInfoService microInfoService;

    @Autowired
    private IBizCashoutFeeService cashoutFeeService;

    @Autowired
    private RuoYiConfig config;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private IBizCashoutRecordsService cashoutRecordsService;

    @Autowired
    private IBizMerchBillService merchBillService;

    @Autowired
    private IBizMerchantService merchantService;

    @Resource
    private BizWalletMapper bizWalletMapper;

    @Autowired
    private IBizShareDetailService bizShareDetailService;

    @Autowired
    private IBizEarningsService bizEarningsService;

    @Autowired
    private IBizSubAccountService bizSubAccountService;

    @Autowired
    private IBizMerchantService bizMerchantService;

    @Autowired
    private IBizPosMachineService bizPosMachineService;

    @Autowired
    private IBizTrackRecordService bizTrackRecordService;

    @Autowired
    private IBizTransactionAmount bizTransactionAmountService;

    @Autowired
    private BizMerchantReceiverServiceImpl bizMerchantReceiverService;

    @Autowired
    private FeiShunSettlementMapper feiShunSettlementMapper;

    @Autowired
    private   PosPCommonParamConfig PosPCommonParamConfig;

    @Autowired
    private IBizMicroInfoService bizMicroInfoService;

    //API对接配置 --商户签名密钥
    String signGenerationKey = "b0f2225345674c36aaa8da44e1c05e56";
    //API对接配置 --默认签名方式
    String signType = "SHA256";
    //API对接配置 --商户ID
    String merchantId = "k34zj89kCA958qJMF1fC";
    //API对接配置 --渠道ID
    String partnerId = "JRMF";
    //下发公司id
    String id = "10247019";

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    private static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS).build();

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizWallet> queryList(BizWallet bizWallet) {
        LambdaQueryWrapper<BizWallet> lqw = Wrappers.lambdaQuery();
        if (bizWallet.getUserId() != null) {
            lqw.eq(BizWallet::getUserId, bizWallet.getUserId());
        }
        if (bizWallet.getProfitAmount() != null) {
            lqw.eq(BizWallet::getProfitAmount, bizWallet.getProfitAmount());
        }
        if (bizWallet.getProfitTaxAmount() != null) {
            lqw.eq(BizWallet::getProfitTaxAmount, bizWallet.getProfitTaxAmount());
        }
        if (bizWallet.getRewardAmount() != null) {
            lqw.eq(BizWallet::getRewardAmount, bizWallet.getRewardAmount());
        }
        if (bizWallet.getRewordTaxAmount() != null) {
            lqw.eq(BizWallet::getRewordTaxAmount, bizWallet.getRewordTaxAmount());
        }
        if (bizWallet.getWalletAmount() != null) {
            lqw.eq(BizWallet::getWalletAmount, bizWallet.getWalletAmount());
        }
        if (StringUtils.isNotBlank(bizWallet.getCashoutStatus())) {
            lqw.eq(BizWallet::getCashoutStatus, bizWallet.getCashoutStatus());
        }
        if (StringUtils.isNotBlank(bizWallet.getPayPassword())) {
            lqw.eq(BizWallet::getPayPassword, bizWallet.getPayPassword());
        }
        if (StringUtils.isNotBlank(bizWallet.getVar1())) {
            lqw.eq(BizWallet::getVar1, bizWallet.getVar1());
        }
        if (StringUtils.isNotBlank(bizWallet.getVar2())) {
            lqw.eq(BizWallet::getVar2, bizWallet.getVar2());
        }
        if (StringUtils.isNotBlank(bizWallet.getVar3())) {
            lqw.eq(BizWallet::getVar3, bizWallet.getVar3());
        }
        if (StringUtils.isNotBlank(bizWallet.getVar4())) {
            lqw.eq(BizWallet::getVar4, bizWallet.getVar4());
        }
        if (StringUtils.isNotBlank(bizWallet.getVar5())) {
            lqw.eq(BizWallet::getVar5, bizWallet.getVar5());
        }
        return this.list(lqw);
    }

    @Override
    public void emptyWallet(Long userId) {
        BizWallet wallets = bizWalletMapper.selectWalletList(userId);
        String key = wallets.getSecretKey();
        String money = DESHelperUtil.decrypt(key, wallets.getProfitAmount());
        String profitAmount = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0.00));
        String rewardAmount = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0.00));
        String coverAmount = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0.00));
        String flowAmount = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0.00));
        String walletAmount = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0.00));
        String activityIntegral = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0));
        BizWallet bizWallet = new BizWallet();
        bizWallet.setRewardAmount(rewardAmount);
        bizWallet.setProfitAmount(profitAmount);
        bizWallet.setCoverAmount(coverAmount);
        bizWallet.setFlowAmount(flowAmount);
        bizWallet.setWalletAmount(walletAmount);
        bizWallet.setActivityIntegral(activityIntegral);
        bizWallet.setWalletId(wallets.getWalletId());
        bizWalletMapper.updateBizWallet(bizWallet);
    }

    @Override
    public int getMyWalletIsNull() {
        List<BizWallet> wallets = bizWalletMapper.getMyWalletIsNull();
        for(BizWallet bizWallet: wallets){
            String key = bizWallet.getSecretKey();
            String coverAmount = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0.00));
            String flowAmount = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(0.00));
            BizWallet bizWallet1 = new BizWallet();
            bizWallet1.setCoverAmount(coverAmount);
            bizWallet1.setFlowAmount(flowAmount);
            bizWallet1.setWalletId(bizWallet.getWalletId());
            bizWalletMapper.updateBizWalletCF(bizWallet1);
        }
        return 1;
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizWallet getMyWallet(WalletDTO walletDTO) {
        LambdaQueryWrapper<BizWallet> lqw = Wrappers.lambdaQuery();
        if (walletDTO.getUserId() != null) {
            lqw.eq(BizWallet::getUserId, walletDTO.getUserId());
        }
        return this.getOne(lqw);
    }

    @Override
    public void setPayPassword(WalletDTO walletDTO) {
        BizWallet wallet = this.getMyWallet(walletDTO);
        //TODO：这里还需要加一层密码密文解密功能，即前端传输过来的是密码密文（加密算法协商解决），解密后保存到本地数据库
        wallet.setPayPassword(SecurityUtils.encryptPassword(walletDTO.getPayPassword()));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizWallet getMyWalletByUserId(Long userId) {
        LambdaQueryWrapper<BizWallet> wallQuery = Wrappers.lambdaQuery();
        wallQuery.eq(BizWallet::getUserId, userId);
        BizWallet wallet = this.getOne(wallQuery);
        return wallet;
    }

    @Override
    @Transactional
    public synchronized AjaxResult doCashOut(CashOutDTO cashOutDTO) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success("预支付提现数据获取成功-未执行任何操作");
        // 账户信息
        cashOutDTO.setEncryptionCardno(0); //不加密卡号
        CashOutVO cashOutVO = microInfoService.getMerchMicroInfoByUserIdAndAccountType(cashOutDTO);
        // 提现费用信息
        BizCashoutFee cashoutFee = cashoutFeeService.getCashoutFeeByType(cashOutDTO);
        // 开始处理   判断提现金额 是否小于等于账户余额
        String key = cashOutVO.getSecretkey();// 获得key
        String secWalletAmount = cashOutVO.getWalletAmount();// 钱包总金额
        // 获得加密的金额
        String secCashOutAmount = cashOutDTO.getCashOutAmount();
        // 解密提现数据
        String cashOutAmountStr = DESHelperUtil.decrypt(key, secCashOutAmount);
        BigDecimal cashOutAmount = new BigDecimal(cashOutAmountStr);
        if (cashOutDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            if (cashOutAmount.compareTo(profitAmount) == 1) { // 大于
                return AjaxResult.error("结算账户余额不足，请重试");
            }
        } else if (cashOutDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            if (cashOutAmount.compareTo(rewardAmount) == 1) { // 大于
                return AjaxResult.error("奖励账户余额不足，请重试");
            }
        } else {
            return AjaxResult.error("请输入accountType账户类型，1-结算账户 2-奖励账户");
        }

        String merPrivate = config.getMerPrivate();
        //商户应用ID
        String appId = config.getAppId();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = df.format(new Date());

        SecClient secClient = new SecClient(SecGatewayConstants.SERVER_URL, "settle.remit.api.payment", appId, merPrivate, "001", timestamp, 20000, 20000);
        // 提现的扣费金额=服务费+费率   100-2 98
        BigDecimal serviceCharge = cashoutFee.getServiceCharge();//服务费
        BigDecimal rate = cashoutFee.getRate();//结算账户费率
        if (cashOutDTO.getAccountType() == 2) {
            rate = cashoutFee.getRewardRate(); //奖励账户费率
        }
        // 需要支付的手续费
        BigDecimal rateFee = cashOutAmount.multiply(rate);
        // 累计需要费用  手续费+服务费
        BigDecimal totalServiceFee = serviceCharge.add(rateFee);
        // 对服务费四舍五入
        String calcTotalServiceFee = BigDecimalUtil.getRoundString(totalServiceFee);
        // 需要支付给用户的费用
        BigDecimal paymentFee = cashOutAmount.subtract(new BigDecimal(calcTotalServiceFee));
        String orderAmt = BigDecimalUtil.getString(paymentFee);//打款金额(元)
        String recvCustName = cashOutVO.getMerchIdcardName();//收款者姓名
        String recvMobile = cashOutVO.getMerchBankMobile();//收款者手机号
        String recvIdType = "IDENTITY（居民身份证）";//收款者证件类型
        String recvIdNo = cashOutVO.getMerchIdcard();//收款证件号
        String recvBankName = cashOutVO.getMerchBank();//收款银行
        String recvCardNo = cashOutVO.getMerchBankCardno();//收款者银行卡号

        //业务参数构建
        RemitBatchRequestDTO remitBatchRequestDTO = new RemitBatchRequestDTO();
        String custBatchNo = UUID.randomUUID().toString().replace("-", "");
        remitBatchRequestDTO.setCustBatchNo(custBatchNo); //商户批次号
        remitBatchRequestDTO.setBatchNum(1);//批次总笔数
        //new BigDecimal 时请写string类型 防止精度丢失
        remitBatchRequestDTO.setBatchAmt(new BigDecimal(orderAmt));//批次总金额

        remitBatchRequestDTO.setServerCallbackUrl("http://www.poshb.cn:8081/noauth/payment/callBack");//打款结果异步通知地址

        List<RemitDetailRequestDTO> list = new ArrayList<RemitDetailRequestDTO>();
        RemitDetailRequestDTO detail_1 = new RemitDetailRequestDTO();
        detail_1.setCustNo(appId);//商户应用ID
        // 订单编号
        String orderNo = OrderUtil.randomOrderNo();
        System.out.println("cust_1  :  " + orderNo);
        detail_1.setCustOrderNo(orderNo);//商户订单号
        //new BigDecimal 时请写string类型 防止精度丢失
        detail_1.setOrderAmt(new BigDecimal(orderAmt));//打款金额
        detail_1.setRecvCustName(recvCustName);//收款者姓名
        detail_1.setRecvMobile(recvMobile);//收款者手机号
        detail_1.setRecvIdType(recvIdType);//收款者证件类型
        detail_1.setRecvIdNo(recvIdNo);//收款整证件号
        detail_1.setRecvCardNo(recvCardNo);//收款者银行卡号
        detail_1.setRecvBankName(recvBankName);//收款银行
        list.add(detail_1);

        remitBatchRequestDTO.setRemitDetailList(list);

        //--------------------------------------------

        // 钱包信息
        BizWallet wallet = walletService.getMyWalletByUserId(cashOutDTO.getUserId());
        // 钱包金额要做减法
        // 获得总金额
        String walletAmountStr = DESHelperUtil.decrypt(key, secWalletAmount);
        BigDecimal walletAmount = new BigDecimal(walletAmountStr);
        if (cashOutDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            // 做减法
            profitAmount = profitAmount.subtract(cashOutAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
        } else if (cashOutDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 做减法
            rewardAmount = rewardAmount.subtract(cashOutAmount);
            // 加密
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            wallet.setRewardAmount(rewardAmountMoneyStr);
        }

        // 钱包总额做减法
        walletAmount = walletAmount.subtract(cashOutAmount);
        // 加密钱包总额
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        walletService.saveOrUpdate(wallet);


        // 生成支付记录信息
        BizCashoutRecords cashoutRecords = new BizCashoutRecords();
        cashoutRecords.setWalletId(wallet.getWalletId());// 钱包id
        cashoutRecords.setCashoutAmount(cashOutAmount);// 提现金额
        cashoutRecords.setDealAccount(recvCardNo);  //提现银行账户
        cashoutRecords.setDealBank(recvBankName);  //提现所属银行
        cashoutRecords.setCashoutType(String.valueOf(cashOutDTO.getAccountType())); //提现类型 1-结算账户 2-奖励账户
        cashoutRecords.setCashoutStatus("6"); //提现状态  0  预约
        cashoutRecords.setCreateBy(cashOutDTO.getUserId());//提现人
        cashoutRecords.setVar1(custBatchNo); // 商户批次号
        cashoutRecords.setVar2(orderNo); //订单号
        cashoutRecords.setVar3(String.valueOf(serviceCharge));// 服务费
        cashoutRecords.setVar4(BigDecimalUtil.getRoundString(rateFee));// 扣费率费用
        cashoutRecords.setVar5(String.valueOf(walletAmount));// 账户余额
        cashoutRecordsService.save(cashoutRecords); // 保存


        //---------------------------------------------
        System.out.println("---------------支付申请时间：" + timestamp + "------------------申请人：" + recvCustName + ",userId=" + cashOutDTO.getUserId());
        BaseResponse responseDTO = secClient.excute(remitBatchRequestDTO);
        System.out.println(responseDTO.toString());
        System.out.println(responseDTO.getResponse());
        String result = responseDTO.getResponse();
        PrepaymentDTO prepaymentDTO = JSON.parseObject(result, PrepaymentDTO.class);

        if (prepaymentDTO.getCode().equals("0000")) {
            // 成功
            // 提现记录  更新状态为 1
            cashoutRecords.setCashoutStatus("5");
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            System.out.println("余额预支付成功");
            ajaxResult = AjaxResult.success("余额预支付成功");
            ajaxResult.put("data", true);
//            return ajaxResult;

            // 发消息
            String prepaymentMess = "预约提现成功：提现金额：" + cashOutAmount + "元，手续费" + calcTotalServiceFee + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。";
            System.out.println(prepaymentMess);
            BizMessageRecords prepaymentMessageRecords = new BizMessageRecords();
            prepaymentMessageRecords.setMsgContent(prepaymentMess);// 消息内容
            prepaymentMessageRecords.setMsgType(3); // 消息类型  3
            prepaymentMessageRecords.setReadStatus(0); // 消息未读
            prepaymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(cashOutDTO.getUserId(), prepaymentMessageRecords);// 发送消息

        } else if (prepaymentDTO.getCode().equals("0001")) {
            // 提现记录  更新状态为 0
            cashoutRecords.setCashoutStatus("4");
            // 获得提现记录
            BizCashoutRecords cashoutRecord = cashoutRecordsService.getCashoutRecordsByCustBatchNo(custBatchNo);
            Long userId = cashoutRecord.getCreateBy();
            // 钱退回
            BizWallet walletBack = walletService.getMyWalletByUserId(userId);
            String secProfitAmount = walletBack.getProfitAmount();//获得结算账户余额
            String secRewardAmount = walletBack.getRewardAmount();// 获得奖励数据
            String keys = walletBack.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(keys, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(keys, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 预支付出去的金额为
            BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            }
            BigDecimal walletAmounts = profitAmount.add(rewardAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(rewardAmount));
            String walletAmountMoneyStrs = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(walletAmounts));
            walletBack.setProfitAmount(profitAmountMoneyStr);
            walletBack.setRewardAmount(rewardAmountMoneyStr);
            walletBack.setWalletAmount(walletAmountMoneyStrs);
            walletBack.setSecretKey(keys);
            // 保存钱包信息
            walletService.saveOrUpdate(walletBack);
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            System.out.println("余额预支付失败-参数为空或格式错误");
            ajaxResult = AjaxResult.error("余额预支付失败-参数为空或格式错误");
            ajaxResult.put("data", false);
        } else if (prepaymentDTO.getCode().equals("9999")) {
            // 提现记录  更新状态为 0
            cashoutRecords.setCashoutStatus("4");
            // 获得提现记录
            BizCashoutRecords cashoutRecord = cashoutRecordsService.getCashoutRecordsByCustBatchNo(custBatchNo);
            Long userId = cashoutRecord.getCreateBy();
            // 钱退回
            BizWallet walletBack = walletService.getMyWalletByUserId(userId);
            String secProfitAmount = walletBack.getProfitAmount();//获得结算账户余额
            String secRewardAmount = walletBack.getRewardAmount();// 获得奖励数据
            String keys = walletBack.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(keys, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(keys, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 预支付出去的金额为
            BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            }
            BigDecimal walletAmounts = profitAmount.add(rewardAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(rewardAmount));
            String walletAmountMoneyStrs = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(walletAmounts));
            walletBack.setProfitAmount(profitAmountMoneyStr);
            walletBack.setRewardAmount(rewardAmountMoneyStr);
            walletBack.setWalletAmount(walletAmountMoneyStrs);
            walletBack.setSecretKey(keys);
            // 保存钱包信息
            walletService.saveOrUpdate(walletBack);
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            System.out.println("余额预支付失败-系统异常");
            ajaxResult = AjaxResult.error("余额预支付失败-系统异常");
            ajaxResult.put("data", false);
        } else if (prepaymentDTO.getCode().equals("9001")) {
            // 提现记录  更新状态为 0
            cashoutRecords.setCashoutStatus("4");
            // 获得提现记录
            BizCashoutRecords cashoutRecord = cashoutRecordsService.getCashoutRecordsByCustBatchNo(custBatchNo);
            Long userId = cashoutRecord.getCreateBy();
            // 钱退回
            BizWallet walletBack = walletService.getMyWalletByUserId(userId);
            String secProfitAmount = walletBack.getProfitAmount();//获得结算账户余额
            String secRewardAmount = walletBack.getRewardAmount();// 获得奖励数据
            String keys = walletBack.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(keys, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(keys, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 预支付出去的金额为
            BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            }
            BigDecimal walletAmounts = profitAmount.add(rewardAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(rewardAmount));
            String walletAmountMoneyStrs = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(walletAmounts));
            walletBack.setProfitAmount(profitAmountMoneyStr);
            walletBack.setRewardAmount(rewardAmountMoneyStr);
            walletBack.setWalletAmount(walletAmountMoneyStrs);
            walletBack.setSecretKey(keys);
            // 保存钱包信息
            walletService.saveOrUpdate(walletBack);
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            System.out.println("余额预支付失败-账户不存");
            ajaxResult = AjaxResult.error("余额预支付失败-账户不存");
            ajaxResult.put("data", false);
        } else if (prepaymentDTO.getCode().equals("9002")) {
            // 提现记录  更新状态为 0
            cashoutRecords.setCashoutStatus("4");
            // 获得提现记录
            BizCashoutRecords cashoutRecord = cashoutRecordsService.getCashoutRecordsByCustBatchNo(custBatchNo);
            Long userId = cashoutRecord.getCreateBy();
            // 钱退回
            BizWallet walletBack = walletService.getMyWalletByUserId(userId);
            String secProfitAmount = walletBack.getProfitAmount();//获得结算账户余额
            String secRewardAmount = walletBack.getRewardAmount();// 获得奖励数据
            String keys = walletBack.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(keys, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(keys, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 预支付出去的金额为
            BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            }
            BigDecimal walletAmounts = profitAmount.add(rewardAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(rewardAmount));
            String walletAmountMoneyStrs = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(walletAmounts));
            walletBack.setProfitAmount(profitAmountMoneyStr);
            walletBack.setRewardAmount(rewardAmountMoneyStr);
            walletBack.setWalletAmount(walletAmountMoneyStrs);
            walletBack.setSecretKey(keys);
            // 保存钱包信息
            walletService.saveOrUpdate(walletBack);
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            System.out.println("余额预支付失败-账户余额不足");
            ajaxResult = AjaxResult.error("余额预支付失败-系统繁忙");
            ajaxResult.put("data", false);
        } else if (prepaymentDTO.getCode().equals("5003")) {
            // 提现记录  更新状态为 0
            cashoutRecords.setCashoutStatus("4");
            // 获得提现记录
            BizCashoutRecords cashoutRecord = cashoutRecordsService.getCashoutRecordsByCustBatchNo(custBatchNo);
            Long userId = cashoutRecord.getCreateBy();
            // 钱退回
            BizWallet walletBack = walletService.getMyWalletByUserId(userId);
            String secProfitAmount = walletBack.getProfitAmount();//获得结算账户余额
            String secRewardAmount = walletBack.getRewardAmount();// 获得奖励数据
            String keys = walletBack.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(keys, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(keys, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 预支付出去的金额为
            BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            }
            BigDecimal walletAmounts = profitAmount.add(rewardAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(rewardAmount));
            String walletAmountMoneyStrs = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(walletAmounts));
            walletBack.setProfitAmount(profitAmountMoneyStr);
            walletBack.setRewardAmount(rewardAmountMoneyStr);
            walletBack.setWalletAmount(walletAmountMoneyStrs);
            walletBack.setSecretKey(keys);
            // 保存钱包信息
            walletService.saveOrUpdate(walletBack);
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            System.out.println("余额预支付失败-超过限额");
            ajaxResult = AjaxResult.error("余额预支付失败-超过限额");
            ajaxResult.put("data", false);
        } else if (prepaymentDTO.getCode().equals("0010")) {
            // 提现记录  更新状态为 0
            cashoutRecords.setCashoutStatus("4");
            // 获得提现记录
            BizCashoutRecords cashoutRecord = cashoutRecordsService.getCashoutRecordsByCustBatchNo(custBatchNo);
            Long userId = cashoutRecord.getCreateBy();
            // 钱退回
            BizWallet walletBack = walletService.getMyWalletByUserId(userId);
            String secProfitAmount = walletBack.getProfitAmount();//获得结算账户余额
            String secRewardAmount = walletBack.getRewardAmount();// 获得奖励数据
            String keys = walletBack.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(keys, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(keys, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 预支付出去的金额为
            BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            }
            BigDecimal walletAmounts = profitAmount.add(rewardAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(rewardAmount));
            String walletAmountMoneyStrs = DESHelperUtil.encrypt(keys, BigDecimalUtil.getString(walletAmounts));
            walletBack.setProfitAmount(profitAmountMoneyStr);
            walletBack.setRewardAmount(rewardAmountMoneyStr);
            walletBack.setWalletAmount(walletAmountMoneyStrs);
            walletBack.setSecretKey(keys);
            // 保存钱包信息
            walletService.saveOrUpdate(walletBack);
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            System.out.println("余额预支付失败-客户状态非法");
            ajaxResult = AjaxResult.error("余额预支付失败-客户状态非法");
            ajaxResult.put("data", false);
        }
        return ajaxResult;
    }

    @Override
    @Transactional
    public synchronized String paymentCallBack(Map<String, String> params, String bizContent) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(new Date());
        System.out.println("-------------------------------" + strDate + "---------------------------------------");
        System.out.println("------------------------------支付接口回调---------------------------------");
        System.out.println("----------------------------------------------------------------------");
        System.out.println("进入回调服务.");
        //云享平台公钥
        String secPublicKey = config.getSecPublicKey();
        try {
            System.out.println("参数：{} " + JsonUtils.ObjectTojson(params));
            boolean flag = SecSignature.rsaCheckV2(params, secPublicKey, SecGatewayConstants.CHARSET_UTF8, SecGatewayConstants.SIGN_TYPE_RSA2);
            System.out.println("验签结果：{} " + flag);
            System.out.println("业务Json:{} " + bizContent);
            if (flag) {
                PaymentCallBackDTO callBackDTO = JSON.parseObject(bizContent, PaymentCallBackDTO.class);
                // 获得商户批次号
                String custBatchNo = callBackDTO.getCustBatchNo();
                // 获得提现记录
                BizCashoutRecords cashoutRecords = cashoutRecordsService.getCashoutRecordsByCustBatchNo(custBatchNo);
                Long userId = cashoutRecords.getCreateBy();
                if (callBackDTO.getFailList() == null || callBackDTO.getFailList().size() == 0) {
                    // 成功
                    // 发消息
                    String var3 = cashoutRecords.getVar3();
                    String var4 = cashoutRecords.getVar4();
                    BigDecimal serviceFee = new BigDecimal(var3);
                    BigDecimal rateFee = new BigDecimal(var4);
                    BigDecimal totalServiceFee = serviceFee.add(rateFee);
                    BigDecimal orderAmt = cashoutRecords.getCashoutAmount().subtract(totalServiceFee);
                    String walletAmount = cashoutRecords.getVar5();
                    /*String paymentMess = "您的提现已成功到账，提现金额：" + cashoutRecords.getCashoutAmount() + "元，手续费"
                            + serviceFee + "元，实际到账金额为："
                            + orderAmt + "元，账户余额为：" + walletAmount + "元。提现到"+cashoutRecords.getDealBank()+
                            "提现订单号是："+cashoutRecords.getVar2()+"。";*/
                    String paymentMess = "您的提现已成功到账，提现金额：" + cashoutRecords.getCashoutAmount() + "元，实际到账金额为："
                            + orderAmt + "元，账户余额为：" + walletAmount + "元。提现到" + cashoutRecords.getDealBank() +
                            ",提现订单号是：" + cashoutRecords.getVar2();
                    System.out.println(paymentMess);
                    BizMessageRecords paymentMessageRecords = new BizMessageRecords();
                    paymentMessageRecords.setMsgContent(paymentMess);// 消息内容
                    paymentMessageRecords.setMsgType(4); // 消息类型  4
                    paymentMessageRecords.setReadStatus(0); // 消息未读
                    paymentMessageRecords.setAdviceType(1); // 业务消息
                    webSocketServer.sendInfo(userId, paymentMessageRecords);// 发送消息
                    // 提现记录  更新状态为 1
                    cashoutRecords.setCashoutStatus("1");
                    cashoutRecords.setMsgId(paymentMessageRecords.getMsgId()); // 存储记录中对应的消息id
                    cashoutRecordsService.saveOrUpdate(cashoutRecords);
                    // 生账单
                    BizMerchBill merchBill = new BizMerchBill();
                    BizMerchant merchant = merchantService.getMerchantByUserId(userId); //商户信息
                    merchBill.setMerchId(merchant.getMerchId());// 商户id
                    merchBill.setMerchName(merchant.getMerchName());// 商户名称
                    merchBill.setBillType("4");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
                    Date date = cashoutRecords.getCreateTime();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    merchBill.setBillDate(sdf.format(date)); //账单日期  与提现日期一致
                    merchBill.setCashoutRecordsId(cashoutRecords.getCashoutId());// 提现id
                    merchBill.setAmount(cashoutRecords.getCashoutAmount().negate()); // 提现存的是负值
                    merchBillService.save(merchBill); // 存账单数据
                } else {
                    // 失败
                    PaymentFailDTO failDTO = callBackDTO.getFailList().get(0);
                    // 钱退回
                    BizWallet wallet = walletService.getMyWalletByUserId(userId);
                    String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
                    String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
                    String key = wallet.getSecretKey();// 获得key
                    // 解密数据
                    String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
                    String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
                    // 转换成BigDecimal类型
                    BigDecimal profitAmount = new BigDecimal(profitAmountStr);
                    BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
                    // 预支付出去的金额为
                    BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
                    // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
                    String cashoutType = cashoutRecords.getCashoutType();
                    if ("1".equals(cashoutType)) {//1-结算账户
                        profitAmount = profitAmount.add(paymentMoney);
                    } else if ("2".equals(cashoutType)) {//2-奖励账户
                        rewardAmount = rewardAmount.add(paymentMoney);
                    } else {
                        return "SUCCESS";
                    }
                    BigDecimal walletAmount = profitAmount.add(rewardAmount);
                    // 加密
                    String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
                    String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
                    String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
                    wallet.setProfitAmount(profitAmountMoneyStr);
                    wallet.setRewardAmount(rewardAmountMoneyStr);
                    wallet.setWalletAmount(walletAmountMoneyStr);
                    wallet.setSecretKey(key);
                    // 保存钱包信息
                    walletService.saveOrUpdate(wallet);
                    // 发消息
                    String paymentFailMess = "您的提现失败，提现金额" + cashoutRecords.getCashoutAmount() + "元已经返回您的余额请注意查收，提现订单号" +
                            cashoutRecords.getVar2() + "，失败原因：" + failDTO.getErrorMsg();
                    System.out.println(paymentFailMess);
                    BizMessageRecords paymentFailMessageRecords = new BizMessageRecords();
                    paymentFailMessageRecords.setMsgContent(paymentFailMess);// 消息内容
                    paymentFailMessageRecords.setMsgType(5); // 消息类型  5
                    paymentFailMessageRecords.setReadStatus(0); // 消息未读
                    paymentFailMessageRecords.setAdviceType(1); // 业务消息
                    webSocketServer.sendInfo(userId, paymentFailMessageRecords);// 发送消息
                    // 提现记录  更新状态为 0  失败
                    cashoutRecords.setCashoutStatus("0");
                    cashoutRecords.setMsgId(paymentFailMessageRecords.getMsgId()); // 存储记录中对应的消息id
                    cashoutRecords.setErrorMsg(failDTO.getErrorMsg());// 存储失败原因
                    cashoutRecordsService.saveOrUpdate(cashoutRecords);
                }
            }

        } catch (SecGatewayException e) {
            e.printStackTrace();
        }
        return "SUCCESS";
    }

    @Override
    @Transactional
    public String queryWalletInfo(List<BizShareDetail> list, ShareDetailDTO shareDetailDTO) {
        for (int i = 0; i < list.size(); i++) {
            // 通过merch_id 去查询钱包信息
            BizWallet bizWallet = bizWalletMapper.queryWalletInfo(list.get(i).getMerchId());
            String key = bizWallet.getSecretKey();// 获得密钥
            String amount = bizWallet.getWalletAmount();// 获得钱包余额
            String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
            String rewardAmount = bizWallet.getRewardAmount();// 获得奖励账户余额
            // 解密
            String walletAmountStr = DESHelperUtil.decrypt(key, amount);
            String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(key, rewardAmount);
            // 转换类型
            BigDecimal bigProfit = new BigDecimal(profitAmountStr);
            BigDecimal bigReward = new BigDecimal(rewardAmountStr);
            BigDecimal bigWallet = new BigDecimal(walletAmountStr);
            if (list.get(i).getCheckStatus() == 0) {// 代表分润未审核
                // 不存入余额 账单 收益
                continue;
            }
            if (list.get(i).getCheckStatus() == 1) {// 审核失败
                // 不存入余额
                continue;
            }
            if (list.get(i).getCheckStatus() == 2) {// 审核成功
                // 将四项税后的钱存入钱包中
                BigDecimal bigProfitAmount = bigProfit.add(list.get(i).getFourAfterTax());
                BigDecimal bigWalletAmount = bigReward.add(bigProfitAmount);
                // 加密
                String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
                String rewardMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigReward));
                String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfitAmount));
                bizWallet.setWalletAmount(walletMoney);
                bizWallet.setProfitAmount(profitMoney);
                bizWallet.setRewardAmount(rewardMoney);
                bizWallet.setSecretKey(key);
                walletService.saveOrUpdate(bizWallet);// 把钱存入表中
                // 把分润表里的状态改为已结算状态
                String result = bizShareDetailService.updateCheckStatus(list.get(i));
                // 生成账单
                BizMerchBill merchBill = new BizMerchBill();
                BizMerchant merchant = merchantService.getMerchantByMerchId(list.get(i).getMerchId());
                merchBill.setMerchId(merchant.getMerchId());// 商户id
                merchBill.setMerchName(merchant.getMerchName());// 商户名称
                merchBill.setBillType("2");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
                merchBill.setVar5(list.get(i).getId().toString());// 把分润主键存入账单var5中
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                merchBill.setBillDate(sdf.format(date)); // 账单日期
                merchBill.setAmount(list.get(i).getFourAfterTax());// 分润所分的钱
                merchBillService.save(merchBill); // 存账单数据
                // 生成收益单 在账单表中查出
                BizEarnings bizEarnings = new BizEarnings();
                shareDetailDTO.setMerchId(list.get(i).getMerchId());// 存入商户的merch_id
                // 在账单表中查出奖励总额
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                Date date1 = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date1); // 设置为当前时间
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
                date1 = calendar.getTime();
                String accDate = format.format(date1);
                bizEarnings.setOrderTime(accDate);
                BigDecimal awardAmount = merchBillService.queryAwardAmount(shareDetailDTO);
                bizEarnings.setMerchId(list.get(i).getMerchId());// merch_id 存入收益表
                bizEarnings.setActivateMoney(awardAmount);// 存入奖励总额
                bizEarnings.setCloseMoney(list.get(i).getFourAfterTax());// 五项税后钱存入
                bizEarnings.setCreateTime(sdf.format(date));// 存入创建时间
                bizEarnings.setAggregateAmount(awardAmount.add(list.get(i).getFourAfterTax()));// 存入总金额
                // 存收益表
                bizEarningsService.saveOrUpdate(bizEarnings);
            }
            if (list.get(i).getCheckStatus() == 3) {
                // 已经结算 不需要操作
                continue;
            }
        }
        return "SUCCESS";
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizWallet> queryAllWallet() {
        List<BizWallet> list = bizWalletMapper.queryAllWallet();
        return list;
    }

    @Override
    public void saveTimeoutIntegral(BizTimeoutIntegral bizTimeoutIntegral) {
        bizWalletMapper.saveTimeoutIntegra(bizTimeoutIntegral);
    }

    @Override
    @DataSource
    public List<BizTimeoutIntegral> queryNotTimeoutOrder() {
        return bizWalletMapper.queryNotTimeoutOrder();
    }

    @Override
    public void updateTemporaryIntegral(BizTimeoutIntegral bizTimeoutIntegral) {
        bizWalletMapper.updateTemporaryIntegral(bizTimeoutIntegral);
    }

    @Override
    @DataSource
    public BizWallet getWalletInfoByMerchId(BizTimeoutIntegral bizTimeoutIntegral) {
        return bizWalletMapper.getWalletInfoByMerchId(bizTimeoutIntegral);
    }

    @Override
    public void updateTemporaryIntegralOver(BizTimeoutIntegral bizTimeoutIntegral) {
        bizWalletMapper.updateTemporaryIntegralOver(bizTimeoutIntegral);
    }

    @Override
    @Transactional
    public synchronized AjaxResult pay(CashOutDTO cashOutDTO) {
        AjaxResult ajaxResult = AjaxResult.success("预支付提现");
        // 账户信息
        cashOutDTO.setEncryptionCardno(0); //不加密卡号
        CashOutVO cashOutVO = microInfoService.getMerchMicroInfoByUserIdAndAccountType(cashOutDTO);
        // 提现费用信息
        BizCashoutFee cashoutFee = cashoutFeeService.getCashoutFeeByType(cashOutDTO);
        // 开始处理   判断提现金额 是否小于等于账户余额
        String key = cashOutVO.getSecretkey();// 获得key
        String secWalletAmount = cashOutVO.getWalletAmount();// 钱包总金额
        // 获得加密的金额
        String secCashOutAmount = cashOutDTO.getCashOutAmount();
        // 解密提现数据

        // ---------------------------------这里做测试用的 记得改回来-----------------------------------

        String cashOutAmountStr = DESHelperUtil.decrypt(key, secCashOutAmount);
        BigDecimal cashOutAmount = new BigDecimal(cashOutAmountStr);
        if (cashOutDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            if (cashOutAmount.compareTo(profitAmount) == 1) { // 大于
                return AjaxResult.error("结算账户余额不足，请重试");
            }
        } else if (cashOutDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            if (cashOutAmount.compareTo(rewardAmount) == 1) { // 大于
                return AjaxResult.error("奖励账户余额不足，请重试");
            }
        } else {
            return AjaxResult.error("请输入accountType账户类型，1-结算账户 2-奖励账户");
        }
        // 提现的扣费金额=服务费+费率   100-2 98
        BigDecimal serviceCharge = cashoutFee.getServiceCharge();//服务费
//        BigDecimal rate = cashoutFee.getRate();//结算账户费率
//        if(cashOutDTO.getAccountType() == 2){
        BigDecimal rate = cashoutFee.getRewardRate(); //奖励账户费率
//        }
        // 需要支付的手续费
        BigDecimal rateFee = cashOutAmount.multiply(rate);
        // 累计需要费用  手续费+服务费
        BigDecimal totalServiceFee = serviceCharge.add(rateFee);
        // 对服务费四舍五入
        String calcTotalServiceFee = BigDecimalUtil.getRoundString(totalServiceFee);
        // 需要支付给用户的费用
        BigDecimal paymentFee = cashOutAmount.subtract(new BigDecimal(calcTotalServiceFee));
        String orderAmt = BigDecimalUtil.getString(paymentFee);//打款金额(元)
        //--------------------------------------------

        // 钱包信息
        BizWallet wallet = walletService.getMyWalletByUserId(cashOutDTO.getUserId());
        // 钱包金额要做减法
        // 获得总金额
        String walletAmountStr = DESHelperUtil.decrypt(key, secWalletAmount);
        BigDecimal walletAmount = new BigDecimal(walletAmountStr);
        if (cashOutDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            // 做减法
            profitAmount = profitAmount.subtract(cashOutAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
        } else if (cashOutDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 做减法
            rewardAmount = rewardAmount.subtract(cashOutAmount);
            // 加密
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            wallet.setRewardAmount(rewardAmountMoneyStr);
        }

        // 钱包总额做减法
        walletAmount = walletAmount.subtract(cashOutAmount);
        // 加密钱包总额
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        walletService.saveOrUpdate(wallet);

        // 生成支付记录信息
        BizCashoutRecords cashoutRecords = new BizCashoutRecords();
        cashoutRecords.setWalletId(wallet.getWalletId());// 钱包id
        cashoutRecords.setCashoutAmount(cashOutAmount);// 提现金额
        cashoutRecords.setDealAccount(cashOutVO.getMerchBankCardno());  //提现银行账户
        cashoutRecords.setDealBank(cashOutVO.getMerchBank());  //提现所属银行
        cashoutRecords.setCashoutType(String.valueOf(cashOutDTO.getAccountType())); //提现类型 1-结算账户 2-奖励账户
        cashoutRecords.setCashoutStatus("6"); //提现状态  0  预约
        cashoutRecords.setCreateBy(cashOutDTO.getUserId());//提现人
        /*cashoutRecords.setVar1(custBatchNo); // 商户批次号
        cashoutRecords.setVar2(orderNo); //订单号*/
        cashoutRecords.setVar3(String.valueOf(serviceCharge));// 服务费
        cashoutRecords.setVar4(BigDecimalUtil.getRoundString(rateFee));// 扣费率费用
        cashoutRecords.setVar5(String.valueOf(walletAmount));// 账户余额
        cashoutRecordsService.save(cashoutRecords); // 保存

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = df.format(new Date());
        System.out.println("---------------易支付支付申请时间：" + timestamp + "------------------userId=" + cashOutDTO.getUserId());
        ApiBaseResult result = callAygApiPay(cashOutVO, paymentFee, cashoutRecords); // paymentFee 打款金额
        System.out.println("--------------" + result + "-------------------");
        if (result.getCode().equals("0000")) {// 0000代表明确下单成功（不代表支付结果）
            System.out.println(result.getMsg());
            // 发消息
            String prepaymentMess = "预约提现成功：提现金额：" + cashOutAmount + "元，手续费" + calcTotalServiceFee + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。";
            System.out.println(prepaymentMess);
            BizMessageRecords prepaymentMessageRecords = new BizMessageRecords();
            prepaymentMessageRecords.setMsgContent(prepaymentMess);// 消息内容
            prepaymentMessageRecords.setMsgType(3); // 消息类型  3
            prepaymentMessageRecords.setReadStatus(0); // 消息未读
            prepaymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(cashOutDTO.getUserId(), prepaymentMessageRecords);// 发送消息

            // 获得请求流水号 reqNo
            String reqNo = result.getData().get("reqNo").toString();
            // 获得平台订单号 orderNo
            String orderNo = result.getData().get("orderNo").toString();
            // 获得企业系统内部订单号 outOrderNo
            String outOrderNo = result.getData().get("outOrderNo").toString();
            cashoutRecords.setVar1(reqNo); // 商户批次号修改为企业系统内部订单号
            cashoutRecords.setVar2(outOrderNo); // 订单号修改为请求流水号
            cashoutRecordsService.saveOrUpdate(cashoutRecords); // 重新保存一下
            ajaxResult = AjaxResult.success("支付成功，请关注回调接口。");
            ajaxResult.put("data", true);
            return ajaxResult;
        } else if (result.getCode().equals("2000") || result.getCode().equals("2001")) {
            // 2000 代表该订单已经发放成功，如果订单是发放中状态，继续保持该状态，等待发放结果异步回调;
            // 2001 代表订单之前已经下单成功，目前正在发放中，继续保持该状态，等待发放结果异步回调即可;
            System.out.println(result.getMsg());
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, result.getMsg());
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("订单已发放。");
            ajaxResult.put("data", false);
            return ajaxResult;
        } else if (result.getCode().equals("1010")) {
            // 1010 输入参数引起的下单失败，可以直接把订单置为失败；
            System.out.println(result.getMsg());
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, result.getMsg());
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        } else if (result.getCode().equals("1020") || result.getCode().equals("1025") || result.getCode().equals("1028") || result.getCode().equals("1030") || result.getCode().equals("1040") || result.getCode().equals("1050") || result.getCode().equals("1060")) {
            // 1020、1025、1028、1030、1040、1050、1060属于接口签名验证的问题，需要订单挂起，然后定位问题；查询订单信息确定问题后再把订单失败
            System.out.println(result.getMsg());
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, result.getMsg());
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        } else if (result.getCode().equals("9999")) {
            // 9999 代表系统未知异常
            System.out.println(result.getMsg());
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, result.getMsg());
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        } else {
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, result.getMsg());
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
    }

    public String httpPostJson(String url, Object params, BizCashoutRecords cashoutRecords) {
        try {
            RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                    , com.jeesuite.common.json.JsonUtils.toJson(params));
            Request request = new Request.Builder().url(url).post(body).build();
            Response response = client.newCall(request).execute();

            try {
                if (response.isSuccessful()) {
                    return response.body().string();
                }
            } finally {
                response.close();
            }
            throw new AygBaseBizException(1001, response.message());
        } catch (Exception e) {
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, "请求第三方错误");
            System.out.println(call_result);
            LOGGER.error("httpGet error", e);
            throw new AygBaseBizException(400, "请求第三方错误");
        }
    }

    @Override
    @Transactional
    public ApiBaseResult deliverapiCallback(ApiBaseParam param) {
        ApiBaseResult result = new ApiBaseResult();
        result.setCode("0000");
        result.setMsg("SUCCESS");
        String signBase = ParameterUtils.objectToSignContent(result);
        PrivateKey appPrivateKey = RsaUtils.loadPrivateKey(config.getAppRsaPrivatekey());
        String signature = RsaUtils.signature(appPrivateKey, signBase);
        result.setSign(signature);
        System.out.println("------------------------回调接收参数---------------------------");
        System.out.println(JSON.toJSONString(param));
        System.out.println("------------------------回调返回参数---------------------------");
        System.out.println(JSON.toJSONString(result));
        // 获得提现记录 通过orderNo
        BizCashoutRecords cashoutRecords = cashoutRecordsService.getCashoutRecordsByCustOrderNo(param.getData().get("outOrderNo"));
        if (cashoutRecords == null) { // 转发到众鑫助手上边
            String url = "http://www.poshb.cn:8081/noauth/ayg/deliverapi_callback";
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("data", param.getData());
            /*Map<String ,String> map = new HashMap<>();
            map.put("appId",param.getAppId());
            map.put("method",param.getAppId());
            map.put("version",param.getAppId());
            map.put("nonce",param.getAppId());
            map.put("timestamp",param.getAppId());
            map.put("sign",param.getAppId());
            map.put("data",data.toString());*/
            String result1 = doPost(url, new Gson().toJson(data));
            System.out.println(result1);
            System.out.println("去 众 鑫 了");
            return result;
        }else {
            Long userId = cashoutRecords.getCreateBy();
            // 处理自己的业务
            if (param.getData().get("code").equals("30")) {
                System.out.println("------------------------支付成功----------------------------");
                // 成功
                // 发消息
                String var3 = cashoutRecords.getVar3();
                String var4 = cashoutRecords.getVar4();
                BigDecimal serviceFee = new BigDecimal(var3);
                BigDecimal rateFee = new BigDecimal(var4);
                BigDecimal totalServiceFee = serviceFee.add(rateFee);
                BigDecimal orderAmt = cashoutRecords.getCashoutAmount().subtract(totalServiceFee);
                String walletAmount = cashoutRecords.getVar5();
                String paymentMess = "您的提现已成功到账，提现金额：" + cashoutRecords.getCashoutAmount() + "元，实际到账金额为："
                        + orderAmt + "元，账户余额为：" + walletAmount + "元。提现到" + cashoutRecords.getDealBank() +
                        ",提现订单号是：" + cashoutRecords.getVar2();
                System.out.println(paymentMess);
                BizMessageRecords paymentMessageRecords = new BizMessageRecords();
                paymentMessageRecords.setMsgContent(paymentMess);// 消息内容
                paymentMessageRecords.setMsgType(4); // 消息类型  4
                paymentMessageRecords.setReadStatus(0); // 消息未读
                paymentMessageRecords.setAdviceType(1); // 业务消息
                webSocketServer.sendInfo(userId, paymentMessageRecords);// 发送消息
                // 提现记录  更新状态为 1
                cashoutRecords.setCashoutStatus("1");
                cashoutRecords.setMsgId(paymentMessageRecords.getMsgId()); // 存储记录中对应的消息id
                cashoutRecordsService.saveOrUpdate(cashoutRecords);
                // 生账单
                BizMerchBill merchBill = new BizMerchBill();
                BizMerchant merchant = merchantService.getMerchantByUserId(userId); //商户信息
                merchBill.setMerchId(merchant.getMerchId());// 商户id
                merchBill.setMerchName(merchant.getMerchName());// 商户名称
                merchBill.setBillType("4");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
                Date date = cashoutRecords.getCreateTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                merchBill.setBillDate(sdf.format(date)); //账单日期  与提现日期一致
                merchBill.setCashoutRecordsId(cashoutRecords.getCashoutId());// 提现id
                merchBill.setAmount(cashoutRecords.getCashoutAmount().negate()); // 提现存的是负值
                merchBillService.save(merchBill); // 存账单数据
            } else if (param.getData().get("code").equals("40")) {
                String message = param.getData().get("msg").toString();
                System.out.println("------------------------支付失败----------------------------");
                if (param.getData().get("exceptionCode").equals("40")) {
                    System.out.println("通用支付异常");
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                } else if (param.getData().get("exceptionCode").equals("4000")) {
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                    message = "系统繁忙";
                    System.out.println("账户余额不足");
                } else if (param.getData().get("exceptionCode").equals("4020")) {
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                    System.out.println("电子签约校验失败");
                } else if (param.getData().get("exceptionCode").equals("4050")) {
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                    System.out.println("三要素校验失败");
                } else if (param.getData().get("exceptionCode").equals("4100")) {
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                    System.out.println("风控拒绝");
                } else if (param.getData().get("exceptionCode").equals("4150")) {
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                    System.out.println("银行卡问题");
                } else if (param.getData().get("exceptionCode").equals("4444")) {
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                    System.out.println("银行卡类型错误");
                } else if (param.getData().get("exceptionCode").equals("9999")) {
                    System.out.println("--------------失败原因：" + param.getData().get("msg") + "------------------------");
                    System.out.println("系统异常");
                }
                // 钱退回
                BizWallet wallet = walletService.getMyWalletByUserId(userId);
                String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
                String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
                String key = wallet.getSecretKey();// 获得key
                // 解密数据
                String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
                String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
                // 转换成BigDecimal类型
                BigDecimal profitAmount = new BigDecimal(profitAmountStr);
                BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
                // 预支付出去的金额为
                BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
                // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
                String cashoutType = cashoutRecords.getCashoutType();
                if ("1".equals(cashoutType)) {//1-结算账户
                    profitAmount = profitAmount.add(paymentMoney);
                } else if ("2".equals(cashoutType)) {//2-奖励账户
                    rewardAmount = rewardAmount.add(paymentMoney);
                } else {
                    return result;
                }
                BigDecimal walletAmount = profitAmount.add(rewardAmount);
                // 加密
                String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
                String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
                String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
                wallet.setProfitAmount(profitAmountMoneyStr);
                wallet.setRewardAmount(rewardAmountMoneyStr);
                wallet.setWalletAmount(walletAmountMoneyStr);
                wallet.setSecretKey(key);
                // 保存钱包信息
                walletService.saveOrUpdate(wallet);
                // 发消息
                String paymentFailMess = "您的提现失败，提现金额" + cashoutRecords.getCashoutAmount() + "元已经返回您的余额请注意查收，提现订单号" +
                        cashoutRecords.getVar2() + "，失败原因：" + message;
                System.out.println(paymentFailMess);
                BizMessageRecords paymentFailMessageRecords = new BizMessageRecords();
                paymentFailMessageRecords.setMsgContent(paymentFailMess);// 消息内容
                paymentFailMessageRecords.setMsgType(5); // 消息类型  5
                paymentFailMessageRecords.setReadStatus(0); // 消息未读
                paymentFailMessageRecords.setAdviceType(1); // 业务消息
                webSocketServer.sendInfo(userId, paymentFailMessageRecords);// 发送消息
                // 提现记录  更新状态为 0  失败
                cashoutRecords.setCashoutStatus("0");
                cashoutRecords.setMsgId(paymentFailMessageRecords.getMsgId()); // 存储记录中对应的消息id
                cashoutRecords.setErrorMsg(param.getData().get("msg").toString());// 存储失败原因
                cashoutRecordsService.saveOrUpdate(cashoutRecords);
            }
            return result;
        }

    }

    /**
     * pos1.0结算打钱
     *
     * @param merchs
     * @return
     */
    @Override
    @Transactional
    public int savePosOneCloseMoney(List<MerchantCloseDTO> merchs, String hostDate ,SynchronizationDataDTO sy) {
        int i = 1;
        String snCode = merchs.get(0).getSnCode();
        BizPosMachine bizPosMachine = bizPosMachineService.selectPosBySnCode(snCode);
        BizMerchant bizMerchant = bizMerchantService.getMerchantByMerchId(bizPosMachine.getMerchId());
        Boolean judgeExtract2 = judgeExtract2(bizMerchant, sy);
        BizRenRunSubsidiesDTO bizRenRunSubsidies = bizPosMachineService.selectBizRenRunSubsidiesKeyWord(sy.getMerchId());
        if (bizRenRunSubsidies!=null){
            fenRun(merchs,hostDate,sy,bizRenRunSubsidies);
            subsidies(merchs,hostDate,sy,bizRenRunSubsidies);
        }
        //不往钱包里打钱了
        if (judgeExtract2){
            for (MerchantCloseDTO merch : merchs) {
                if (merch.getOverMoney().compareTo(new BigDecimal(0.00)) == -1) {
                    merch.setOverMoney(new BigDecimal(0.00));
                }
                // 存一下每个分的账单
                DecimalFormat formater = new DecimalFormat();
                formater.setMaximumFractionDigits(2);
                formater.setGroupingSize(0);
                formater.setRoundingMode(RoundingMode.FLOOR);
                merch.setOverMoney(new BigDecimal(formater.format(merch.getOverMoney())));
                if("1".equals(sy.getIsSecondExecute())) {
                    int b = bizSubAccountService.saveMerchantCloseDTO(merch);
                }
                Long userId = merch.getUserId();
                // 生成账单
                BizMerchBill merchBill = new BizMerchBill();
                BizMerchant merchant = merchantService.getMerchantByMerchId(merch.getMerchId());
                merchBill.setMerchId(merchant.getMerchId());// 商户id
                merchBill.setMerchName(merchant.getMerchName());// 商户名称
                merchBill.setBillType("2");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
                //merchBill.setVar5(list.get(i).getId().toString());// 把分润主键存入账单var5中
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                merchBill.setBillDate(sdf.format(date)); // 账单日期
                merchBill.setAmount(merch.getOverMoney());// 分润所分的钱
                merchBill.setVar4(merch.getUuid());
                //分账为0的不存账单表
                if (!merchBill.getAmount().equals(BigDecimal.ZERO)) {
                    merchBill.setBillDate(hostDate);
                    if("1".equals(sy.getIsSecondExecute())) {
                        merchBillService.save(merchBill); // 存账单数据
                    }
                    //  merchBillService.insertMerchBill(merchBill);
                }
                //存分润明细
                ProfitDeatailDTO profitDeatailDTO = new ProfitDeatailDTO();
                profitDeatailDTO.setTransactionAmountId(merch.getUuid());
                profitDeatailDTO.setParentName(merch.getName());
                profitDeatailDTO.setMerchId(merch.getMerchId());
                profitDeatailDTO.setLevel(i);
                profitDeatailDTO.setRate(merch.getCloseRate());
                profitDeatailDTO.setMoney(merch.getOverMoney().toString());
                profitDeatailDTO.setCreateTime(hostDate);
                if("1".equals(sy.getIsSecondExecute())) {
                    bizSubAccountService.saveProfitDetail(profitDeatailDTO);
                }
                i++;
            }
            //生成追溯记录
            BizTrackRecord bizTrackRecord = new BizTrackRecord();
            bizTrackRecord.setHostDate(String.valueOf(sy.getHost_date()));
            bizTrackRecord.setHostTime(sy.getHost_time());
            bizTrackRecord.setMerchantNo(sy.getMerchant_no());
            bizTrackRecord.setTerminalNo(sy.getTerminal_no());
            bizTrackRecord.setPan(sy.getPan());
            bizTrackRecord.setAmnount(String.valueOf(sy.getAmnount()));
            bizTrackRecord.setAddiAmount(String.valueOf(sy.getAddi_amount()));
            bizTrackRecord.setFeeName(sy.getFee_name());
            bizTrackRecord.setCardType(String.valueOf(sy.getCard_type()));
            bizTrackRecord.setTransType(String.valueOf(sy.getTrans_type()));
            bizTrackRecord.setEnterMode(sy.getEnter_mode());
            bizTrackRecord.setPosSn(sy.getPos_sn());
            bizTrackRecord.setPosTrace(sy.getPos_trace());
            bizTrackRecord.setChlDate(sy.getChl_date());
            bizTrackRecord.setChlTime(sy.getChl_time());
            bizTrackRecord.setChlMerchantNo(sy.getChl_merchant_no());
            bizTrackRecord.setChlTerminalNo(sy.getChl_terminal_no());
            bizTrackRecord.setRetrirefnum(sy.getRetrirefnum());
            bizTrackRecord.setAuthCode(sy.getAuth_code());
            bizTrackRecord.setHostRetCode(sy.getHost_ret_code());
            bizTrackRecord.setBankCode(sy.getBank_code());
            bizTrackRecord.setAcqCertificate(sy.getAcq_certificate());
            bizTrackRecord.setAcqName(sy.getAcq_name());
            bizTrackRecord.setAcqAccountNo(sy.getAcq_account_no());
            bizTrackRecord.setOrderNo(sy.getOrder_no());
            bizTrackRecord.setMerchId(sy.getMerchId());
            bizTrackRecord.setUuid(Long.parseLong(merchs.get(0).getUuid()));
            bizTrackRecordService.save(bizTrackRecord);
            return 1;
        }else {
            for (MerchantCloseDTO merch : merchs) {
                if (merch.getOverMoney().compareTo(new BigDecimal(0.00)) == -1) {
                    merch.setOverMoney(new BigDecimal(0.00));
                }
                // 存一下每个分的账单
                DecimalFormat formater = new DecimalFormat();
                formater.setMaximumFractionDigits(2);
                formater.setGroupingSize(0);
                formater.setRoundingMode(RoundingMode.FLOOR);
                merch.setOverMoney(new BigDecimal(formater.format(merch.getOverMoney())));
                if("1".equals(sy.getIsSecondExecute())){
                    int b = bizSubAccountService.saveMerchantCloseDTO(merch);
                }
                if (merch.getUserId()==2){
                    Long userId = merch.getUserId();
                    //判断一下追溯开关 比例  金额  为真就不给钱
                    BizWallet bizWallet = walletService.getMyWalletByUserId(userId);
                    String key = bizWallet.getSecretKey();// 获得密钥
                    String amount = bizWallet.getWalletAmount();// 获得钱包余额
                    String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
                    String rewardAmount = bizWallet.getRewardAmount();// 获得奖励账户余额
                    String coverAmount = bizWallet.getCoverAmount();// 获得服务费账户余额
                    String flowAmount = bizWallet.getFlowAmount();// 获得流量费账户余额
                    // 解密
                    String walletAmountStr = DESHelperUtil.decrypt(key, amount);
                    String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
                    String rewardAmountStr = DESHelperUtil.decrypt(key, rewardAmount);
                    String coverAmountStr = DESHelperUtil.decrypt(key, coverAmount);
                    String flowAmountStr = DESHelperUtil.decrypt(key, flowAmount);
                    // 转换类型
                    BigDecimal bigProfit = new BigDecimal(profitAmountStr);
                    BigDecimal bigReward = new BigDecimal(rewardAmountStr);
                    /*服务费*/
                    BigDecimal bigCover = new BigDecimal(coverAmountStr);
                    /*流量费*/
                    BigDecimal bigFlow = new BigDecimal(flowAmountStr);
                    BigDecimal bigWallet = new BigDecimal(walletAmountStr);
                    BigDecimal bigProfitAmount = bigProfit.add(merch.getOverMoney());
                    BigDecimal bigWalletAmount = bigReward.add(bigProfitAmount).add(bigCover).add(bigFlow);
                    // 加密
                    String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
                    String rewardMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigReward));
                    String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfitAmount));
                    bizWallet.setWalletAmount(walletMoney);
                    bizWallet.setProfitAmount(profitMoney);
                    bizWallet.setRewardAmount(rewardMoney);
                    bizWallet.setSecretKey(key);
                    if("1".equals(sy.getIsSecondExecute())) {
                        walletService.saveOrUpdate(bizWallet);// 把钱存入表中
                    }
                    // 生成账单
                    BizMerchBill merchBill = new BizMerchBill();
                    BizMerchant merchant = merchantService.getMerchantByMerchId(merch.getMerchId());
                    merchBill.setMerchId(merchant.getMerchId());// 商户id
                    merchBill.setMerchName(merchant.getMerchName());// 商户名称
                    merchBill.setBillType("2");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
                    //merchBill.setVar5(list.get(i).getId().toString());// 把分润主键存入账单var5中
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    merchBill.setBillDate(sdf.format(date)); // 账单日期
                    merchBill.setAmount(merch.getOverMoney());// 分润所分的钱
                    merchBill.setVar4(merch.getUuid());
                    //分账为0的不存账单表
                    if (!merchBill.getAmount().equals(BigDecimal.ZERO)) {
                        merchBill.setBillDate(hostDate);
                        if("1".equals(sy.getIsSecondExecute())) {
                            merchBillService.save(merchBill); // 存账单数据
                        }
                        //  merchBillService.insertMerchBill(merchBill);
                    }
                }else {
                    Long userId = merch.getUserId();
                    //判断一下追溯开关 比例  金额  为真就不给钱
                    BizWallet bizWallet = walletService.getMyWalletByUserId(userId);
                    String key = bizWallet.getSecretKey();// 获得密钥
                    String amount = bizWallet.getWalletAmount();// 获得钱包余额
                    String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
                    String rewardAmount = bizWallet.getRewardAmount();// 获得奖励账户余额
                    String coverAmount = bizWallet.getCoverAmount();// 获得服务费账户余额
                    String flowAmount = bizWallet.getFlowAmount();// 获得流量费账户余额
                    // 解密
                    String walletAmountStr = DESHelperUtil.decrypt(key, amount);
                    String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
                    String rewardAmountStr = DESHelperUtil.decrypt(key, rewardAmount);
                    String coverAmountStr = DESHelperUtil.decrypt(key, coverAmount);
                    String flowAmountStr = DESHelperUtil.decrypt(key, flowAmount);
                    // 转换类型
                    BigDecimal bigProfit = new BigDecimal(profitAmountStr);
                    BigDecimal bigReward = new BigDecimal(rewardAmountStr);
                    /*服务费*/
                    BigDecimal bigCover = new BigDecimal(coverAmountStr);
                    /*流量费*/
                    BigDecimal bigFlow = new BigDecimal(flowAmountStr);
                    BigDecimal bigWallet = new BigDecimal(walletAmountStr);
                    BigDecimal bigProfitAmount = bigProfit.add(merch.getOverMoney().subtract((merch.getFenRunMoney()==null)?new BigDecimal("0"):merch.getFenRunMoney()));
                    BigDecimal bigWalletAmount = bigReward.add(bigProfitAmount).add(bigCover).add(bigFlow);
                    // 加密
                    String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
                    String rewardMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigReward));
                    String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfitAmount));
                    bizWallet.setWalletAmount(walletMoney);
                    bizWallet.setProfitAmount(profitMoney);
                    bizWallet.setRewardAmount(rewardMoney);
                    bizWallet.setSecretKey(key);
                    if("1".equals(sy.getIsSecondExecute())) {
                        walletService.saveOrUpdate(bizWallet);// 把钱存入表中
                    }
                    // 生成账单
                    BizMerchBill merchBill = new BizMerchBill();
                    BizMerchant merchant = merchantService.getMerchantByMerchId(merch.getMerchId());
                    merchBill.setMerchId(merchant.getMerchId());// 商户id
                    merchBill.setMerchName(merchant.getMerchName());// 商户名称
                    merchBill.setBillType("2");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
                    //merchBill.setVar5(list.get(i).getId().toString());// 把分润主键存入账单var5中
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    merchBill.setBillDate(sdf.format(date)); // 账单日期
                    merchBill.setAmount(merch.getOverMoney().subtract((merch.getFenRunMoney()==null)?new BigDecimal("0"):merch.getFenRunMoney()));// 分润所分的钱
                    merchBill.setVar4(merch.getUuid());
                    //分账为0的不存账单表
                    if (!merchBill.getAmount().equals(BigDecimal.ZERO)) {
                        merchBill.setBillDate(hostDate);
                        if("1".equals(sy.getIsSecondExecute())) {
                            merchBillService.save(merchBill); // 存账单数据
                        }
                        //  merchBillService.insertMerchBill(merchBill);
                    }
                }
                //存分润明细
                ProfitDeatailDTO profitDeatailDTO = new ProfitDeatailDTO();
                profitDeatailDTO.setTransactionAmountId(merch.getUuid());
                profitDeatailDTO.setParentName(merch.getName());
                profitDeatailDTO.setMerchId(merch.getMerchId());
                profitDeatailDTO.setLevel(i);
                profitDeatailDTO.setRate(merch.getCloseRate());
                profitDeatailDTO.setMoney(merch.getOverMoney().toString());
                profitDeatailDTO.setCreateTime(hostDate);
                if("0".equals(sy.getIsSecondExecute())) {
                    bizSubAccountService.saveProfitDetail(profitDeatailDTO);
                }else{
                    if("1".equals(sy.getSilenceType())){
                        profitDeatailDTO.setActualRate(merch.getCloseRate());
                        profitDeatailDTO.setActualMoney(merch.getOverMoney().toString());
                        bizSubAccountService.updateProfitDetail(profitDeatailDTO);
                    }else{
                        profitDeatailDTO.setActualRate(merch.getCloseRate());
                        profitDeatailDTO.setActualMoney(merch.getOverMoney().toString());
                        bizSubAccountService.saveProfitDetail(profitDeatailDTO);
                    }

                }
                i++;
            }
            return 1;
        }
    }

    @Override
    public int updateWalletByUserId(BizWallet bizWallet1) {
        return bizWalletMapper.updateWalletByUserId(bizWallet1);
    }

    @Override
    public int insertBizServiceBills(CashbackRecordDTO list) {
        return bizWalletMapper.insertBizServiceBills(list);
    }

    @Override
    public int savePosOneCloseMoney2(List<MerchantCloseDTO> merchs, String hostDate, SynchronizationDataDTO sy) {
        int i = 1;
        for (MerchantCloseDTO merch : merchs) {
            if (merch.getOverMoney().compareTo(new BigDecimal(0.00)) == -1) {
                merch.setOverMoney(new BigDecimal(0.00));
            }
            Long userId = merch.getUserId();
            //判断一下追溯开关 比例  金额  为真就不给钱
            BizWallet bizWallet = walletService.getMyWalletByUserId(userId);
            String key = bizWallet.getSecretKey();// 获得密钥
            String amount = bizWallet.getWalletAmount();// 获得钱包余额
            String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
            String rewardAmount = bizWallet.getRewardAmount();// 获得奖励账户余额
            // 解密
            String walletAmountStr = DESHelperUtil.decrypt(key, amount);
            String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(key, rewardAmount);
            // 转换类型
            BigDecimal bigProfit = new BigDecimal(profitAmountStr);
            BigDecimal bigReward = new BigDecimal(rewardAmountStr);
            BigDecimal bigWallet = new BigDecimal(walletAmountStr);

            BigDecimal bigProfitAmount = bigProfit.add(merch.getOverMoney());
            BigDecimal bigWalletAmount = bigReward.add(bigProfitAmount);
            // 加密
            String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
            String rewardMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigReward));
            String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfitAmount));
            bizWallet.setWalletAmount(walletMoney);
            bizWallet.setProfitAmount(profitMoney);
            bizWallet.setRewardAmount(rewardMoney);
            bizWallet.setSecretKey(key);
            walletService.saveOrUpdate(bizWallet);// 把钱存入表中
            i++;
        }
        return 1;
    }

    private int fenRun(List<MerchantCloseDTO> merchs, String hostDate, SynchronizationDataDTO sy,BizRenRunSubsidiesDTO bizRenRunSubsidies) {
        /*是否分润*/
        String isFenRun=new String("0");
        /*用来判断和补贴*/
        String compare=new String("0");
        //二次分润
        // 判断是不是设备所属
        //如果——分到的钱是——不等于：0
        //  判断：二次分润开关
        //      开
        //          FR——————费率：58————比例：10%
        //              如果————费率————大于等于——费率：58
        //                  最终的钱-*-比例：10%——分给总账户
        if(isFenRun.equals(compare)){
            if (!(merchs.get(0).getOverMoney().compareTo(BigDecimal.ZERO) == 0)) {
                if (isFenRun.equals(compare)) {
                    isFenRun = "1";
                    /*查询二次分润开关*/
                        /*判断开关*/
                        if (bizRenRunSubsidies.getFrswitchs() .equals("1")) {
                            /*判断 交易的费率>=二次分润费率  */
                            boolean test1=new BigDecimal(sy.getFee_name().replace("实时", "")).compareTo(new BigDecimal(bizRenRunSubsidies.getRate().replace("实时", ""))) == 1;
                            boolean test2=new BigDecimal(sy.getFee_name().replace("实时", "")).compareTo(new BigDecimal(bizRenRunSubsidies.getRate().replace("实时", ""))) == 0;
                            if (new BigDecimal(sy.getFee_name().replace("实时", "")).compareTo(new BigDecimal(bizRenRunSubsidies.getRate().replace("实时", ""))) == 1 || new BigDecimal(sy.getFee_name().replace("实时", "")).compareTo(new BigDecimal(bizRenRunSubsidies.getRate().replace("实时", ""))) == 0) {
                                /*分润分给总账户的钱*/
                                BigDecimal totalShareProfit = merchs.get(0).getOverMoney().multiply(new BigDecimal(bizRenRunSubsidies.getPercentage()).divide(new BigDecimal("100"))).setScale(2,BigDecimal.ROUND_DOWN );
                                /*直属代理扣除二次分润的钱*/
                                merchs.get(0).setFenRunMoney(totalShareProfit);

                                BizWallet bizWallet = walletService.getMyWalletByUserId(merchs.get(merchs.size() - 1).getUserId());
                                String key = bizWallet.getSecretKey();// 获得密钥
                                String amount = bizWallet.getWalletAmount();// 获得钱包余额
                                String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
                                String rewardAmount = bizWallet.getRewardAmount();// 获得奖励账户余额
                                String coverAmount = bizWallet.getCoverAmount();// 获得服务费账户余额
                                String flowAmount = bizWallet.getFlowAmount();// 获得流量费账户余额
                                // 解密
                                String walletAmountStr = DESHelperUtil.decrypt(key, amount);
                                String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
                                String rewardAmountStr = DESHelperUtil.decrypt(key, rewardAmount);
                                String coverAmountStr = DESHelperUtil.decrypt(key, coverAmount);
                                String flowAmountStr = DESHelperUtil.decrypt(key, flowAmount);
                                // 转换类型
                                BigDecimal bigProfit = new BigDecimal(profitAmountStr);
                                BigDecimal bigReward = new BigDecimal(rewardAmountStr);
                                /*服务费*/
                                BigDecimal bigCover = new BigDecimal(coverAmountStr);
                                /*流量费*/
                                BigDecimal bigFlow = new BigDecimal(flowAmountStr);
                                BigDecimal bigWallet = new BigDecimal(walletAmountStr);

                                BigDecimal bigProfitAmount = bigProfit.add(totalShareProfit);
                                BigDecimal bigWalletAmount = bigWallet.add(bigProfitAmount).add(bigReward).add(bigCover).add(bigFlow);
                                // 加密
                                String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
                                String rewardMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigReward));
                                String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfitAmount));
                                String coverMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigCover));
                                String flowMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigFlow));

                                bizWallet.setWalletAmount(walletMoney);
                                bizWallet.setProfitAmount(profitMoney);
                                bizWallet.setRewardAmount(rewardMoney);
                                bizWallet.setCoverAmount(coverMoney);
                                bizWallet.setFlowAmount(flowMoney);
                                bizWallet.setSecretKey(key);
                                walletService.saveOrUpdate(bizWallet);// 把钱存入表中
                                // 生成账单
                                BizMerchBill merchBill = new BizMerchBill();
                                BizMerchant merchant = merchantService.getMerchantByMerchId(merchs.get(merchs.size() - 1).getMerchId());
                                merchBill.setMerchId(merchant.getMerchId());// 商户id
                                merchBill.setMerchName(merchant.getMerchName());// 商户名称
                                merchBill.setBillType("2");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金 6-流量费 7-服务费 8-补贴
                                //merchBill.setVar5(list.get(i).getId().toString());// 把分润主键存入账单var5中
                                Date date = new Date();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                merchBill.setBillDate(sdf.format(date)); // 账单日期
                                merchBill.setAmount(totalShareProfit);// 分润所分的钱
                                merchBill.setBillDate(hostDate);
                                merchBillService.save(merchBill); // 存账单数据
                            }
                        }
                    }
            }
        }
        return 1;
    }
    private int subsidies(List<MerchantCloseDTO> merchs, String hostDate, SynchronizationDataDTO sy,BizRenRunSubsidiesDTO bizRenRunSubsidies) {
        /*是否补贴*/
        String isSubsidy=new String("0");
        /*用来判断和补贴*/
        String compare=new String("0");
        /*补贴钱*/
        BigDecimal subsidyMoney=new BigDecimal("0");
        if(isSubsidy.equals(compare)){
            //补贴
            //判断：补贴开关
            //  开
            //      交易金额-*-（1：20000）——分给设备所属
            /*查看补贴是否开关*/
            if (bizRenRunSubsidies.getBtswitchs() .equals("1")) {
                if (isSubsidy.equals(compare)) {
                    isSubsidy = "1";
                    /*比例*/
                    BigDecimal ratio = new BigDecimal(bizRenRunSubsidies.getSubsidyHead()).divide(new BigDecimal(bizRenRunSubsidies.getSubsidyEnd()));
                    /*直属代理补贴的钱*/
                    subsidyMoney=new BigDecimal(sy.getAmnount()).multiply(ratio).setScale(2,BigDecimal.ROUND_DOWN );

                    BizWallet bizWallet = walletService.getMyWalletByUserId(merchs.get(0).getUserId());
                    String key = bizWallet.getSecretKey();// 获得密钥
                    String amount = bizWallet.getWalletAmount();// 获得钱包余额
                    String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
                    String rewardAmount = bizWallet.getRewardAmount();// 获得奖励账户余额
                    String coverAmount = bizWallet.getCoverAmount();// 获得服务费账户余额
                    String flowAmount = bizWallet.getFlowAmount();// 获得流量费账户余额
                    // 解密
                    String walletAmountStr = DESHelperUtil.decrypt(key, amount);
                    String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
                    String rewardAmountStr = DESHelperUtil.decrypt(key, rewardAmount);
                    String coverAmountStr = DESHelperUtil.decrypt(key, coverAmount);
                    String flowAmountStr = DESHelperUtil.decrypt(key, flowAmount);

                    BigDecimal bigProfit = new BigDecimal(profitAmountStr);
                    BigDecimal bigReward = new BigDecimal(rewardAmountStr);
                    /*服务费*/
                    BigDecimal bigCover = new BigDecimal(coverAmountStr);
                    /*流量费*/
                    BigDecimal bigFlow = new BigDecimal(flowAmountStr);
                    BigDecimal bigWallet = new BigDecimal(walletAmountStr);

                    BigDecimal bigRewardAmount = bigReward.add(subsidyMoney);
                    BigDecimal bigWalletAmount = bigProfit.add(bigRewardAmount).add(bigCover).add(bigFlow);

                    // 加密
                    String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
                    String rewardMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigRewardAmount));
                    String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfit));
                    String coverMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigCover));
                    String flowMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigFlow));

                    bizWallet.setWalletAmount(walletMoney);
                    bizWallet.setProfitAmount(profitMoney);
                    bizWallet.setRewardAmount(rewardMoney);
                    bizWallet.setCoverAmount(coverMoney);
                    bizWallet.setFlowAmount(flowMoney);
                    bizWallet.setSecretKey(key);
                    walletService.saveOrUpdate(bizWallet);// 把钱存入表中
                    // 生成账单
                    BizMerchBill merchBill = new BizMerchBill();
                    BizMerchant merchant = merchantService.getMerchantByMerchId(merchs.get(0).getMerchId());
                    merchBill.setMerchId(merchant.getMerchId());// 商户id
                    merchBill.setMerchName(merchant.getMerchName());// 商户名称
                    merchBill.setBillType("8");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金 6-流量费 7-服务费 8-补贴
                    //merchBill.setVar5(list.get(i).getId().toString());// 把分润主键存入账单var5中
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    merchBill.setBillDate(sdf.format(date)); // 账单日期
                    merchBill.setAmount(subsidyMoney);// 分润所分的钱
                    merchBill.setBillDate(hostDate);
                    merchBillService.save(merchBill); // 存账单数据
                }
            }
        }
        return 1;
    }

    @Override
    public void independentAccount(List<BizProfitDeatail> list) {
        for (BizProfitDeatail merch : list) {
            BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(merch.getMerchId());
            Long userId = merchantByMerchId.getUserId();

            BizWallet bizWallet = walletService.getMyWalletByUserId(userId);
            String key = bizWallet.getSecretKey();// 获得密钥
            String amount = bizWallet.getWalletAmount();// 获得钱包余额
            String profitAmount = bizWallet.getProfitAmount();// 获得结算账户总额
            String rewardAmount = bizWallet.getRewardAmount();// 获得奖励账户余额
            // 解密
            String walletAmountStr = DESHelperUtil.decrypt(key, amount);
            String profitAmountStr = DESHelperUtil.decrypt(key, profitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(key, rewardAmount);
            // 转换类型
            BigDecimal bigProfit = new BigDecimal(profitAmountStr);
            BigDecimal bigReward = new BigDecimal(rewardAmountStr);
            BigDecimal bigWallet = new BigDecimal(walletAmountStr);

            BigDecimal bigProfitAmount = bigProfit.add(new BigDecimal(merch.getMoney()));
            BigDecimal bigWalletAmount = bigReward.add(bigProfitAmount);
            // 加密
            String walletMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigWalletAmount));
            String rewardMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigReward));
            String profitMoney = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(bigProfitAmount));
            bizWallet.setWalletAmount(walletMoney);
            bizWallet.setProfitAmount(profitMoney);
            bizWallet.setRewardAmount(rewardMoney);
            bizWallet.setSecretKey(key);
            boolean b = walletService.saveOrUpdate(bizWallet);// 把钱存入表中
        }
    }

    @Override
    public AjaxResult payDLG(CashOutDTO cashOutDTO) {
        AjaxResult ajaxResult = AjaxResult.success("预支付提现");
        // 账户信息
        cashOutDTO.setEncryptionCardno(0); //不加密卡号
        CashOutVO cashOutVO = microInfoService.getMerchMicroInfoByUserIdAndAccountType(cashOutDTO);
        // 提现费用信息
        BizCashoutFee cashoutFee = cashoutFeeService.getCashoutFeeByType(cashOutDTO);
        // 开始处理   判断提现金额 是否小于等于账户余额
        String key = cashOutVO.getSecretkey();// 获得key
        String secWalletAmount = cashOutVO.getWalletAmount();// 钱包总金额
        // 获得加密的金额
        String secCashOutAmount = cashOutDTO.getCashOutAmount();
        // 解密提现数据

        // ---------------------------------这里做测试用的 记得改回来-----------------------------------

        String cashOutAmountStr = DESHelperUtil.decrypt(key, secCashOutAmount);
        BigDecimal cashOutAmount = new BigDecimal(cashOutAmountStr);
        if (cashOutDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            if (cashOutAmount.compareTo(profitAmount) == 1) { // 大于
                return AjaxResult.error("结算账户余额不足，请重试");
            }
        } else if (cashOutDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            if (cashOutAmount.compareTo(rewardAmount) == 1) { // 大于
                return AjaxResult.error("奖励账户余额不足，请重试");
            }
        } else {
            return AjaxResult.error("请输入accountType账户类型，1-结算账户 2-奖励账户");
        }
        // 提现的扣费金额=服务费+费率   100-2 98
        BigDecimal serviceCharge = cashoutFee.getServiceCharge();//服务费
//        BigDecimal rate = cashoutFee.getRate();//结算账户费率
//        if(cashOutDTO.getAccountType() == 2){
        BigDecimal rate = cashoutFee.getRewardRate(); //奖励账户费率
//        }
        // 需要支付的手续费
        BigDecimal rateFee = cashOutAmount.multiply(rate);
        // 累计需要费用  手续费+服务费
        BigDecimal totalServiceFee = serviceCharge.add(rateFee);
        // 对服务费四舍五入
        String calcTotalServiceFee = BigDecimalUtil.getRoundString(totalServiceFee);
        // 需要支付给用户的费用
        BigDecimal paymentFee = cashOutAmount.subtract(new BigDecimal(calcTotalServiceFee));
        String orderAmt = BigDecimalUtil.getString(paymentFee);//打款金额(元)
        //--------------------------------------------

        // 钱包信息
        BizWallet wallet = walletService.getMyWalletByUserId(cashOutDTO.getUserId());
        // 钱包金额要做减法
        // 获得总金额
        String walletAmountStr = DESHelperUtil.decrypt(key, secWalletAmount);
        BigDecimal walletAmount = new BigDecimal(walletAmountStr);
        if (cashOutDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            // 做减法
            profitAmount = profitAmount.subtract(cashOutAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
        } else if (cashOutDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 做减法
            rewardAmount = rewardAmount.subtract(cashOutAmount);
            // 加密
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            wallet.setRewardAmount(rewardAmountMoneyStr);
        }

        // 钱包总额做减法
        walletAmount = walletAmount.subtract(cashOutAmount);
        // 加密钱包总额
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        walletService.saveOrUpdate(wallet);
        BizMerchantReceiver bizMerchantReceiver = iBizMerchantReceiverService.selectBizMerchantReceiverByUserId(cashOutDTO.getUserId());
        // 生成支付记录信息
        BizCashoutRecords cashoutRecords = new BizCashoutRecords();
        cashoutRecords.setWalletId(wallet.getWalletId());// 钱包id
        cashoutRecords.setCashoutAmount(cashOutAmount);// 提现金额
        cashoutRecords.setDealAccount(bizMerchantReceiver.getMerchBankCardno());  //提现银行账户
        // cashoutRecords.setDealBank(cashOutVO.getMerchBank());  //提现所属银行
        cashoutRecords.setCashoutType(String.valueOf(cashOutDTO.getAccountType())); //提现类型 1-结算账户 2-奖励账户
        cashoutRecords.setCashoutStatus("6"); //提现状态  0  预约
        cashoutRecords.setCreateBy(cashOutDTO.getUserId());//提现人
        /*cashoutRecords.setVar1(custBatchNo); // 商户批次号
        cashoutRecords.setVar2(orderNo); //订单号*/
        cashoutRecords.setVar3(String.valueOf(serviceCharge));// 服务费
        cashoutRecords.setVar4(BigDecimalUtil.getRoundString(rateFee));// 扣费率费用
        cashoutRecords.setVar5(String.valueOf(walletAmount));// 账户余额
        cashoutRecordsService.save(cashoutRecords); // 保存

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = df.format(new Date());
        System.out.println("---------------点灵工支付申请时间：" + timestamp + "------------------userId=" + cashOutDTO.getUserId());
        String result = bankCardIssue(cashOutVO, paymentFee, cashoutRecords); // paymentFee 打款金额
        System.out.println("--------------" + result + "-------------------");
        JSONObject jsonObject = JSON.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String ret_data = jsonObject.getString("ret_data");
        String ret_msg = jsonObject.getString("ret_msg");
        if (ret_msg.equals("商户余额不足")){
            ret_msg = "操作失败";
        }
        JSONObject object = JSONObject.parseObject(ret_data);
        if (retCode.equals("0000")) {// 0000代表明确下单成功（不代表支付结果）
            System.out.println(ret_msg);
            // 发消息

            String prepaymentMess = "预约提现成功：提现金额：" + cashOutAmount + "元，手续费" + calcTotalServiceFee + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。";
            System.out.println(prepaymentMess);
            BizMessageRecords prepaymentMessageRecords = new BizMessageRecords();
            prepaymentMessageRecords.setMsgContent(prepaymentMess);// 消息内容
            prepaymentMessageRecords.setMsgType(3); // 消息类型  3
            prepaymentMessageRecords.setReadStatus(0); // 消息未读
            prepaymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(cashOutDTO.getUserId(), prepaymentMessageRecords);// 发送消息
            // 获得请求流水号 reqNo
            String reqNo = object.getString("deal_no");
            // 获得企业系统内部订单号 outOrderNo
            String outOrderNo = object.getString("deal_no");
            cashoutRecords.setVar1(reqNo); // 商户批次号修改为企业系统内部订单号
            cashoutRecords.setVar2(outOrderNo); // 订单号修改为请求流水号
            cashoutRecordsService.saveOrUpdate(cashoutRecords); // 重新保存一下
            ajaxResult = AjaxResult.success("支付成功，请关注回调接口。");
            ajaxResult.put("data", true);
            return ajaxResult;
        } else {
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, ret_msg);
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
    }

    @Override
    public String deliverapiCallbackDLG(ReceiverParam param) {
        System.out.println("------------------------回调接收参数---------------------------");
        System.out.println(JSON.toJSONString(param));
        // 获得提现记录 通过orderNo
        BizCashoutRecords cashoutRecords = cashoutRecordsService.getCashoutRecordsByCustOrderNo(param.getDeal_no());
        Long userId = cashoutRecords.getCreateBy();
        // 处理自己的业务
        if (param.getDeal_status().equals("C1")) {
            System.out.println("------------------------支付成功----------------------------");
            // 成功
            // 发消息
            String var3 = cashoutRecords.getVar3();
            String var4 = cashoutRecords.getVar4();
            BigDecimal serviceFee = new BigDecimal(var3);
            BigDecimal rateFee = new BigDecimal(var4);
            BigDecimal totalServiceFee = serviceFee.add(rateFee);
            BigDecimal orderAmt = cashoutRecords.getCashoutAmount().subtract(totalServiceFee);
            String walletAmount = cashoutRecords.getVar5();
            String paymentMess = "您的提现已成功到账，提现金额：" + cashoutRecords.getCashoutAmount() + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。提现到" + cashoutRecords.getDealBank() +
                    ",提现订单号是：" + cashoutRecords.getVar2();
            System.out.println(paymentMess);
            BizMessageRecords paymentMessageRecords = new BizMessageRecords();
            paymentMessageRecords.setMsgContent(paymentMess);// 消息内容
            paymentMessageRecords.setMsgType(4); // 消息类型  4
            paymentMessageRecords.setReadStatus(0); // 消息未读
            paymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(userId, paymentMessageRecords);// 发送消息
            // 生账单
            BizMerchBill merchBill = new BizMerchBill();
            BizMerchant merchant = merchantService.getMerchantByUserId(userId); //商户信息
            merchBill.setMerchId(merchant.getMerchId());// 商户id
            merchBill.setMerchName(merchant.getMerchName());// 商户名称
            merchBill.setBillType("4");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
            Date date = cashoutRecords.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            merchBill.setBillDate(sdf.format(date)); //账单日期  与提现日期一致
            merchBill.setCashoutRecordsId(cashoutRecords.getCashoutId());// 提现id
            merchBill.setAmount(cashoutRecords.getCashoutAmount().negate()); // 提现存的是负值
            merchBillService.save(merchBill); // 存账单数据
            // 提现记录  更新状态为 1
            cashoutRecords.setCashoutStatus("1");
            cashoutRecords.setVar1(param.getRequest_no());
            cashoutRecords.setMsgId(paymentMessageRecords.getMsgId()); // 存储记录中对应的消息id
            cashoutRecordsService.saveOrUpdate(cashoutRecords);

        } else if(param.getDeal_status().equals("C2")){
            String message = param.getFail_detail_msg();
            System.out.println("------------------------支付失败----------------------------");
            // 钱退回
            if (param.getFail_detail_msg().equals("商户余额不足")){
                message = "操作失败";
            }
            BizWallet wallet = walletService.getMyWalletByUserId(userId);
            String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
            String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
            String key = wallet.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 预支付出去的金额为
            BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            } else {
                return "SUCCESS";
            }
            BigDecimal walletAmount = profitAmount.add(rewardAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
            wallet.setRewardAmount(rewardAmountMoneyStr);
            wallet.setWalletAmount(walletAmountMoneyStr);
            wallet.setSecretKey(key);
            // 保存钱包信息
            walletService.saveOrUpdate(wallet);
            // 发消息
            String paymentFailMess = "您的提现失败，提现金额" + cashoutRecords.getCashoutAmount() + "元已经返回您的余额请注意查收，提现订单号" +
                    cashoutRecords.getVar2() + "，失败原因：" + message;
            System.out.println(paymentFailMess);
            BizMessageRecords paymentFailMessageRecords = new BizMessageRecords();
            paymentFailMessageRecords.setMsgContent(paymentFailMess);// 消息内容
            paymentFailMessageRecords.setMsgType(5); // 消息类型  5
            paymentFailMessageRecords.setReadStatus(0); // 消息未读
            paymentFailMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(userId, paymentFailMessageRecords);// 发送消息
            // 提现记录  更新状态为 0  失败
            cashoutRecords.setCashoutStatus("0");
            cashoutRecords.setMsgId(paymentFailMessageRecords.getMsgId()); // 存储记录中对应的消息id
            cashoutRecords.setErrorMsg(param.getFail_detail_msg());// 存储失败原因
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
        }
        return "SUCCESS";
    }


    // 预支付回退
    private String prepaymentCallBack(BizCashoutRecords cashoutRecords, String msg) {
        // 钱退回
        BizWallet wallet = walletService.getMyWalletByUserId(cashoutRecords.getCreateBy());
        String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
        String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
        String key = wallet.getSecretKey();// 获得key
        // 解密数据
        String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
        String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
        // 转换成BigDecimal类型
        BigDecimal profitAmount = new BigDecimal(profitAmountStr);
        BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
        // 预支付出去的金额为
        BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
        // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
        String cashoutType = cashoutRecords.getCashoutType();
        if ("1".equals(cashoutType)) {//1-结算账户
            profitAmount = profitAmount.add(paymentMoney);
        } else if ("2".equals(cashoutType)) {//2-奖励账户
            rewardAmount = rewardAmount.add(paymentMoney);
        } else {
            return "success";
        }
        BigDecimal walletAmount = profitAmount.add(rewardAmount);
        // 加密
        String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
        String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        wallet.setProfitAmount(profitAmountMoneyStr);
        wallet.setRewardAmount(rewardAmountMoneyStr);
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        walletService.saveOrUpdate(wallet);
        // 发消息
        String paymentFailMess = "您的预支付提现失败，提现金额" + cashoutRecords.getCashoutAmount() + "元已经返回您的余额请注意查收，失败原因：" + msg;
        System.out.println(paymentFailMess);
        BizMessageRecords paymentFailMessageRecords = new BizMessageRecords();
        paymentFailMessageRecords.setMsgContent(paymentFailMess);// 消息内容
        paymentFailMessageRecords.setMsgType(5); // 消息类型  5
        paymentFailMessageRecords.setReadStatus(0); // 消息未读
        paymentFailMessageRecords.setAdviceType(1); // 业务消息
        webSocketServer.sendInfo(cashoutRecords.getCreateBy(), paymentFailMessageRecords);// 发送消息
        // 提现记录  更新状态为 0  失败
        cashoutRecords.setCashoutStatus("0");
        cashoutRecords.setMsgId(paymentFailMessageRecords.getMsgId()); // 存储记录中对应的消息id
        cashoutRecords.setErrorMsg(msg);// 存储失败原因
        cashoutRecordsService.saveOrUpdate(cashoutRecords);
        return "call_back_success";
    }

    @SneakyThrows
    @Override
    public AjaxResult payXinLongDLG(BizAgentidAppkeyDTO bizAgentidAppkeyDTO ,SubmitGrantDetailDTO submitGrantDetailDTO, BizMicroInfo bizMicroInfoByMerchId,String natchno) {
        AjaxResult ajaxResult = AjaxResult.success("预支付提现");
        // 账户信息
        submitGrantDetailDTO.setEncryptionCardno(0); //不加密卡号
        CashOutVO cashOutVO = microInfoService.getXinLongMerchMicroInfoByUserIdAndAccountType(submitGrantDetailDTO);
        // 提现费用信息
        BizCashoutFee cashoutFee = cashoutFeeService.getXinLongCashoutFeeByType(submitGrantDetailDTO);
        // 开始处理   判断提现金额 是否小于等于账户余额
        String key = cashOutVO.getSecretkey();// 获得key
        String secWalletAmount = cashOutVO.getWalletAmount();// 钱包总金额
        // 获得加密的金额
        String secCashOutAmount = submitGrantDetailDTO.getCashOutAmount();
        // 解密提现数据

        // ---------------------------------这里做测试用的 记得改回来-----------------------------------

        String cashOutAmountStr = DESHelperUtil.decrypt(key, secCashOutAmount);
        BigDecimal cashOutAmount = new BigDecimal(cashOutAmountStr);
        BigDecimal balnce=this.queryBalance(submitGrantDetailDTO.getUserId());
        System.out.println("账户余额：==="+balnce);
        if (cashOutAmount.compareTo(balnce) == 1) { // 大于
            return AjaxResult.error("发票不足，请重试");
        }
        if (submitGrantDetailDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            if (cashOutAmount.compareTo(profitAmount) == 1) { // 大于
                return AjaxResult.error("结算账户余额不足，请重试");
            }
        } else if (submitGrantDetailDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            if (cashOutAmount.compareTo(rewardAmount) == 1) { // 大于
                return AjaxResult.error("奖励账户余额不足，请重试");
            }
        } else if (submitGrantDetailDTO.getAccountType() == 3) { // 流量费账户提现
            String secCoverAmount = cashOutVO.getCoverAmount();// 获得奖励数据
            // 解密数据
            String coverAmountStr = DESHelperUtil.decrypt(key, secCoverAmount);
            // 转换成BigDecimal类型
            BigDecimal coverAmount = new BigDecimal(coverAmountStr);
            if (cashOutAmount.compareTo(coverAmount) == 1) { // 大于
                return AjaxResult.error("服务费账户余额不足，请重试");
            }
        } else if (submitGrantDetailDTO.getAccountType() == 4) { // 服务费账户提现
            String secFlowAmount = cashOutVO.getFlowAmount();// 获得奖励数据
            // 解密数据
            String flowAmountStr = DESHelperUtil.decrypt(key, secFlowAmount);
            // 转换成BigDecimal类型
            BigDecimal flowAmount = new BigDecimal(flowAmountStr);
            if (cashOutAmount.compareTo(flowAmount) == 1) { // 大于
                return AjaxResult.error("流量费账户余额不足，请重试");
            }
        } else {
            return AjaxResult.error("请输入accountType账户类型，1-分润账户 2-补贴账户 3-服务费账户 4-流量费费账户");
        }
        // 提现的扣费金额=服务费+费率   100-2 98
        BigDecimal serviceCharge = cashoutFee.getServiceCharge();//服务费
        //BigDecimal rate = cashoutFee.getRate();//结算账户费率
        /*if(submitGrantDetailDTO.getAccountType() == 2){
            rate = cashoutFee.getRewardRate(); //奖励账户费率
        }*/
        BigDecimal rate = cashoutFee.getRewardRate(); //奖励账户费率
        // 需要支付的手续费
        BigDecimal rateFee = cashOutAmount.multiply(rate);
        // 累计需要费用  手续费+服务费
        BigDecimal totalServiceFee = serviceCharge.add(rateFee);
        // 对服务费四舍五入
        String calcTotalServiceFee = BigDecimalUtil.getRoundString(totalServiceFee);
        // 需要支付给用户的费用
        BigDecimal paymentFee = cashOutAmount.subtract(new BigDecimal(calcTotalServiceFee));
        String orderAmt = BigDecimalUtil.getString(paymentFee);//打款金额(元)
        //--------------------------------------------

        // 钱包信息
        BizWallet wallet = walletService.getMyWalletByUserId(submitGrantDetailDTO.getUserId());
        // 钱包金额要做减法
        // 获得总金额
        String walletAmountStr = DESHelperUtil.decrypt(key, secWalletAmount);
        BigDecimal walletAmount = new BigDecimal(walletAmountStr);
        if (submitGrantDetailDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            // 做减法
            profitAmount = profitAmount.subtract(cashOutAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
        } else if (submitGrantDetailDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 做减法
            rewardAmount = rewardAmount.subtract(cashOutAmount);
            // 加密
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            wallet.setRewardAmount(rewardAmountMoneyStr);
        }else if (submitGrantDetailDTO.getAccountType() == 3) { // 服务费账户提现
            String secCoverAmount = cashOutVO.getCoverAmount();// 获得服务费数据
            // 解密数据
            String coverAmountStr = DESHelperUtil.decrypt(key, secCoverAmount);
            // 转换成BigDecimal类型
            BigDecimal coverAmount = new BigDecimal(coverAmountStr);
            // 做减法
            coverAmount = coverAmount.subtract(cashOutAmount);
            // 加密
            String coverAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(coverAmount));
            wallet.setCoverAmount(coverAmountMoneyStr);
        }else if (submitGrantDetailDTO.getAccountType() == 4) { // 流量费账户提现
            String secFlowAmount = cashOutVO.getFlowAmount();// 获得流量费数据
            // 解密数据
            String flowAmountStr = DESHelperUtil.decrypt(key, secFlowAmount);
            // 转换成BigDecimal类型
            BigDecimal flowAmount = new BigDecimal(flowAmountStr);
            // 做减法
            flowAmount = flowAmount.subtract(cashOutAmount);
            // 加密
            String flowAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(flowAmount));
            wallet.setFlowAmount(flowAmountMoneyStr);
        }

        // 钱包总额做减法
        walletAmount = walletAmount.subtract(cashOutAmount);
        // 加密钱包总额
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        boolean b=walletService.saveOrUpdate(wallet);
        if(!b){
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
        BizWallet walletn = walletService.getMyWalletByUserId(submitGrantDetailDTO.getUserId());
        BizMerchantReceiver bizMerchantReceiver = iBizMerchantReceiverService.selectBizMerchantReceiverByUserId(submitGrantDetailDTO.getUserId());
        // 生成支付记录信息
        BizCashoutRecords cashoutRecords = new BizCashoutRecords();
        cashoutRecords.setWalletId(wallet.getWalletId());// 钱包id
        cashoutRecords.setCashoutAmount(cashOutAmount);// 提现金额
        cashoutRecords.setDealAccount(bizMerchantReceiver.getMerchBankCardno());  //提现银行账户
        // cashoutRecords.setDealBank(cashOutVO.getMerchBank());  //提现所属银行
        cashoutRecords.setCashoutType(String.valueOf(submitGrantDetailDTO.getAccountType())); //提现类型 1-结算账户 2-奖励账户
        cashoutRecords.setCashoutStatus("6"); //提现状态  0  预约
        cashoutRecords.setCreateBy(submitGrantDetailDTO.getUserId());//提现人
        /*cashoutRecords.setVar1(custBatchNo); // 商户批次号
        cashoutRecords.setVar2(orderNo); //订单号*/
        cashoutRecords.setVar3(String.valueOf(serviceCharge));// 服务费
        cashoutRecords.setVar4(BigDecimalUtil.getRoundString(rateFee));// 扣费率费用
        cashoutRecords.setVar5(DESHelperUtil.decrypt(walletn.getWalletAmount(),walletn.getSecretKey()));// 账户余额
        cashoutRecordsService.save(cashoutRecords); // 保存

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = df.format(new Date());
        System.out.println("---------------薪龙支付申请时间：" + timestamp + "------------------userId=" + submitGrantDetailDTO.getUserId());
        String token= bizMerchantReceiverService.acquireAccessToken(bizAgentidAppkeyDTO);
        JSONObject submitGrantDetail = bankCardIssueXinLong(bizAgentidAppkeyDTO,submitGrantDetailDTO,orderAmt,natchno,bizMicroInfoByMerchId,token); // paymentFee 打款金额
        System.out.println("--------------" + submitGrantDetail + "-------------------");
        String codeDetail=submitGrantDetail.getString("code");
        String messageDetail=submitGrantDetail.getString("message");
        String data1=submitGrantDetail.getString("data");
        if (codeDetail.equals("0000")) {// 0000代表明确下单成功（不代表支付结果）
            System.out.println(data1);
            // 发消息
            String prepaymentMess = "预约提现成功：提现金额：" + cashOutAmount + "元，手续费" + calcTotalServiceFee + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。";
            System.out.println(prepaymentMess);
            BizMessageRecords prepaymentMessageRecords = new BizMessageRecords();
            prepaymentMessageRecords.setMsgContent(prepaymentMess);// 消息内容
            prepaymentMessageRecords.setMsgType(3); // 消息类型  3
            prepaymentMessageRecords.setReadStatus(0); // 消息未读
            prepaymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(submitGrantDetailDTO.getUserId(), prepaymentMessageRecords);// 发送消息
            /*// 获得请求流水号 reqNo
            String reqNo = object.getString("deal_no");
            // 获得企业系统内部订单号 outOrderNo
            String outOrderNo = object.getString("deal_no");*/
            cashoutRecords.setVar1(natchno); // 商户批次号修改为企业系统内部订单号
            cashoutRecords.setVar2(natchno); // 订单号修改为请求流水号
            cashoutRecords.setIsRefund("0"); //是否退款
            cashoutRecordsService.saveOrUpdate(cashoutRecords); // 重新保存一下
            ajaxResult = AjaxResult.success("支付成功，请关注回调接口。");
            ajaxResult.put("data", true);
            return ajaxResult;
        } else {
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, messageDetail);
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
    }

    @Override
    public String deliverapiCallbackXinLongDLG(JSONObject jsonObject) {
        System.out.println("------------------------回调接收参数---------------------------");
        System.out.println(jsonObject);
        // 获得提现记录 通过orderNo
        BizCashoutRecords cashoutRecords = cashoutRecordsService.getCashoutRecordsByCustOrderNo(jsonObject.getString("outer_trade_no"));
        if(cashoutRecords==null){
            return "success";
        }
        Long userId = cashoutRecords.getCreateBy();
        // 处理自己的业务
        if (jsonObject.getString("send_status").equals("11") && jsonObject.getString("withdrawal_status").equals("TRADE_FINISHED")) {
            System.out.println("------------------------支付成功----------------------------");
            // 成功
            // 发消息
            String var3 = cashoutRecords.getVar3();
            String var4 = cashoutRecords.getVar4();
            BigDecimal serviceFee = new BigDecimal(var3);
            BigDecimal rateFee = new BigDecimal(var4);
            BigDecimal totalServiceFee = serviceFee.add(rateFee);
            BigDecimal orderAmt = cashoutRecords.getCashoutAmount().subtract(totalServiceFee);
            String walletAmount = cashoutRecords.getVar5();
            String paymentMess = "您的提现已成功到账，提现金额：" + cashoutRecords.getCashoutAmount() + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。提现到" + cashoutRecords.getDealBank() +
                    ",提现订单号是：" + cashoutRecords.getVar2();
            System.out.println(paymentMess);
            BizMessageRecords paymentMessageRecords = new BizMessageRecords();
            paymentMessageRecords.setMsgContent(paymentMess);// 消息内容
            paymentMessageRecords.setMsgType(4); // 消息类型  4
            paymentMessageRecords.setReadStatus(0); // 消息未读
            paymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(userId, paymentMessageRecords);// 发送消息
            // 生账单
            BizMerchBill merchBill = new BizMerchBill();
            BizMerchant merchant = merchantService.getMerchantByUserId(userId); //商户信息
            merchBill.setMerchId(merchant.getMerchId());// 商户id
            merchBill.setMerchName(merchant.getMerchName());// 商户名称
            merchBill.setBillType("4");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
            Date date = cashoutRecords.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            merchBill.setBillDate(sdf.format(date)); //账单日期  与提现日期一致
            merchBill.setCashoutRecordsId(cashoutRecords.getCashoutId());// 提现id
            merchBill.setAmount(cashoutRecords.getCashoutAmount().negate()); // 提现存的是负值
            merchBillService.save(merchBill); // 存账单数据
            // 提现记录  更新状态为 1
            cashoutRecords.setCashoutStatus("1");
            cashoutRecords.setVar1(jsonObject.getString("inner_trade_no"));
            cashoutRecords.setMsgId(paymentMessageRecords.getMsgId()); // 存储记录中对应的消息id
            cashoutRecordsService.saveOrUpdate(cashoutRecords);
            //返上级税差
            try {
                this.with(merchant,cashoutRecords);
            }catch (Exception e){
                System.out.println("返上级税差异常，错误信息如下");
                e.printStackTrace();
            }
            return "success";
        } else if(jsonObject.getString("send_status").equals("02") && jsonObject.getString("withdrawal_status").equals("TRADE_FAILED")){
            if (cashoutRecords.getIsRefund().equals("0")){
                BizWallet wallet = walletService.getMyWalletByUserId(userId);
                String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
                String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
                String secCoverAmount = wallet.getCoverAmount();// 获得服务费数据
                String secFlowAmount = wallet.getFlowAmount();// 获得流量费数据
                String key = wallet.getSecretKey();// 获得key
                // 解密数据
                String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
                String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
                String coverAmountStr = DESHelperUtil.decrypt(key, secCoverAmount);
                String flowAmountStr = DESHelperUtil.decrypt(key, secFlowAmount);
                // 转换成BigDecimal类型
                BigDecimal profitAmount = new BigDecimal(profitAmountStr);
                BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
                BigDecimal coverAmount = new BigDecimal(coverAmountStr);
                BigDecimal flowAmount = new BigDecimal(flowAmountStr);
                // 预支付出去的金额为
                BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
                // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
                String cashoutType = cashoutRecords.getCashoutType();
                if ("1".equals(cashoutType)) {//1-结算账户
                    profitAmount = profitAmount.add(paymentMoney);
                } else if ("2".equals(cashoutType)) {//2-奖励账户
                    rewardAmount = rewardAmount.add(paymentMoney);
                }else if ("3".equals(cashoutType)) {//2-服务费账户
                    coverAmount = coverAmount.add(paymentMoney);
                }else if ("4".equals(cashoutType)) {//2-流量费账户
                    flowAmount = flowAmount.add(paymentMoney);
                }
                BigDecimal walletAmount = profitAmount.add(rewardAmount).add(coverAmount).add(flowAmount);
                // 加密
                String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
                String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
                String  coverAmountMoneyStr= DESHelperUtil.encrypt(key, BigDecimalUtil.getString(coverAmount));
                String flowAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(flowAmount));
                String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
                wallet.setProfitAmount(profitAmountMoneyStr);
                wallet.setRewardAmount(rewardAmountMoneyStr);
                wallet.setCoverAmount(coverAmountMoneyStr);
                wallet.setFlowAmount(flowAmountMoneyStr);
                wallet.setWalletAmount(walletAmountMoneyStr);
                wallet.setSecretKey(key);
                // 保存钱包信息
                walletService.saveOrUpdate(wallet);
                // 发消息
                String paymentFailMess = "您的提现失败，提现金额" + cashoutRecords.getCashoutAmount() + "元已经返回您的余额请注意查收，提现订单号" +
                        cashoutRecords.getVar2() + "，失败原因：交易失败" +"---错误信息："+jsonObject.getString("error_msg")+"---错误代码："+ jsonObject.getString("error_code");
                System.out.println(paymentFailMess);
                BizMessageRecords paymentFailMessageRecords = new BizMessageRecords();
                paymentFailMessageRecords.setMsgContent(paymentFailMess);// 消息内容
                paymentFailMessageRecords.setMsgType(5); // 消息类型  5
                paymentFailMessageRecords.setReadStatus(0); // 消息未读
                paymentFailMessageRecords.setAdviceType(1); // 业务消息
                webSocketServer.sendInfo(userId, paymentFailMessageRecords);// 发送消息
                // 提现记录  更新状态为 0  失败
                cashoutRecords.setCashoutStatus("0");
                cashoutRecords.setMsgId(paymentFailMessageRecords.getMsgId()); // 存储记录中对应的消息id
                cashoutRecords.setErrorMsg("---错误信息："+jsonObject.getString("error_msg")+"---错误代码："+ jsonObject.getString("error_code"));// 存储失败原因
                cashoutRecords.setIsRefund("1");
                cashoutRecordsService.saveOrUpdate(cashoutRecords);
            }
        }
        return "success";
    }
    public void with(BizMerchant merchant, BizCashoutRecords cashoutRecords) {
        if(merchant.getParentId()==0){
            return;
        }
        SysUser user=posMachineMapper.getUserByUserId(merchant.getUserId());
        BizMerchant merchant1=posMachineMapper.getMerchantByMerchId(merchant.getParentId());
        SysUser parentUser=posMachineMapper.getUserByUserId(merchant1.getUserId());
        BizWallet wallet = walletService.getMyWalletByUserId(parentUser.getUserId());
        // 预支付出去的金额为
        BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
        System.out.println(parentUser.getRate()+"    "+user.getRate());
        if(parentUser.getRate().compareTo(user.getRate())<0){
            paymentMoney=paymentMoney.multiply(user.getRate().subtract(parentUser.getRate())).setScale(2,BigDecimal.ROUND_DOWN);
            String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
            String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
            String secCoverAmount = wallet.getCoverAmount();// 获得服务费数据
            String secFlowAmount = wallet.getFlowAmount();// 获得流量费数据
            String key = wallet.getSecretKey();// 获得key
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            String coverAmountStr = DESHelperUtil.decrypt(key, secCoverAmount);
            String flowAmountStr = DESHelperUtil.decrypt(key, secFlowAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            BigDecimal coverAmount = new BigDecimal(coverAmountStr);
            BigDecimal flowAmount = new BigDecimal(flowAmountStr);

            // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
            String cashoutType = cashoutRecords.getCashoutType();
            if ("1".equals(cashoutType)) {//1-结算账户
                profitAmount = profitAmount.add(paymentMoney);
            } else if ("2".equals(cashoutType)) {//2-奖励账户
                rewardAmount = rewardAmount.add(paymentMoney);
            }else if ("3".equals(cashoutType)) {//2-服务费账户
                coverAmount = coverAmount.add(paymentMoney);
            }else if ("4".equals(cashoutType)) {//2-流量费账户
                flowAmount = flowAmount.add(paymentMoney);
            }
            BigDecimal walletAmount = profitAmount.add(rewardAmount).add(coverAmount).add(flowAmount);
            // 生账单
            BizMerchBill merchBill = new BizMerchBill();
            merchBill.setMerchId(merchant1.getMerchId());// 商户id
            merchBill.setMerchName(merchant1.getMerchName());// 商户名称
            merchBill.setBillType("4");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
            Date date = cashoutRecords.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            merchBill.setBillDate(sdf.format(date)); //账单日期  与提现日期一致
            merchBill.setCashoutRecordsId(cashoutRecords.getCashoutId());// 提现id
            merchBill.setAmount(paymentMoney); // 返税金额
            merchBillService.saveOrUpdate(merchBill); // 存账单数据
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            String  coverAmountMoneyStr= DESHelperUtil.encrypt(key, BigDecimalUtil.getString(coverAmount));
            String flowAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(flowAmount));
            String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
            wallet.setRewardAmount(rewardAmountMoneyStr);
            wallet.setCoverAmount(coverAmountMoneyStr);
            wallet.setFlowAmount(flowAmountMoneyStr);
            wallet.setWalletAmount(walletAmountMoneyStr);
            wallet.setSecretKey(key);
            // 保存钱包信息
            walletService.saveOrUpdate(wallet);
        }
        this.with(merchant1,cashoutRecords);

    }


    @Override
    public JSONObject getSearchMer(BizAgentidAppkeyDTO bizAgentidAppkeyDTO) throws Exception {
        Map<String,Object> data=new HashMap<String,Object>();
        data.put("jnlNo","test001");
        String sign= SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
        System.out.println("data===查询账户余额==提交数据="+data+"----"+bizAgentidAppkeyDTO.toString());
        //业务参数（加密数据）
        String requestBody= AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
        String token= bizMerchantReceiverService.acquireAccessToken(bizAgentidAppkeyDTO);
        JSONObject submitGrantDetail=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"searchMer",sign,requestBody,token);
        return submitGrantDetail;
    }

    public JSONObject bankCardIssueXinLong(BizAgentidAppkeyDTO bizAgentidAppkeyDTO,SubmitGrantDetailDTO submitGrantDetailDTO,String orderAmt,String natchno,BizMicroInfo bizMicroInfoByMerchId,String token) throws Exception {
        Map<String,Object> data=new HashMap<String,Object>();
        data.put("uid",bizAgentidAppkeyDTO.getUid());
        JSONArray jsarr=new JSONArray();
        JSONObject dis=new JSONObject();
        dis.put("natchno",natchno);//
        dis.put("outerInstNatchno",natchno);
        dis.put("idtypename","1");
        dis.put("idcard",bizMicroInfoByMerchId.getMerchIdcard());
        dis.put("mobile",bizMicroInfoByMerchId.getMerchBankMobile());
        dis.put("ccyCode","OTHERBANK");
        dis.put("tranAmount",orderAmt);
        dis.put("inBankName",bizMicroInfoByMerchId.getMerchBank());
        dis.put("inAcctNo",bizMicroInfoByMerchId.getMerchBankCardno());
        dis.put("inAcctName",bizMicroInfoByMerchId.getMerchIdcardName());
        dis.put("cardType","DC");
        dis.put("cardAttribute","C");
        dis.put("bankName",bizMicroInfoByMerchId.getMerchBank());
        jsarr.add(dis);
        System.out.println("-----------------------------"+jsarr.toJSONString());
        data.put("distributionlist",jsarr);
        data.put("notify_url",bizAgentidAppkeyDTO.getTxNotifyUrl().replace("[userid]",submitGrantDetailDTO.getUserId().toString()));
        String sign= SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
        System.out.println("data===单笔对私提现==提交数据="+data);
        //业务参数（加密数据）
        String requestBody= AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
        JSONObject submitGrantDetail=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"submitGrantDetail",sign,requestBody,token);
        return submitGrantDetail;
    }


    private ApiBaseResult callAygApiPay(CashOutVO cashOutVO, BigDecimal amount, BizCashoutRecords cashoutRecords) {
        String url = "https://openapi.opensaas.net.cn/deliver/dlvopenapi/api/app/pay/unified-order";
        Map<String, Object> params = new Hashtable<>();
        params.put("appId", "210817021728176564");
        params.put("method", "ayg.salary.pay");
        params.put("version", "1.0");
        params.put("nonce", "" + System.currentTimeMillis() + new Random().nextInt(1000));
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(new Date());
        params.put("timestamp", strDate);
        params.put("signType", "RSA2");
        Map<String, Object> data = new Hashtable<>();
        data.put("outOrderNo", "10001" + System.currentTimeMillis()); // 企业系统内部订单号
        data.put("amount", amount);
        data.put("memo", "用户" + cashOutVO.getMerchIdcardName() + "提现");
        data.put("accountNo", cashOutVO.getMerchBankCardno());
        data.put("accountName", cashOutVO.getMerchIdcardName());
        data.put("serviceCompanyId", "10003200");
        data.put("idCard", cashOutVO.getMerchIdcard());
        data.put("phone", cashOutVO.getMerchBankMobile());
        params.put("data", data);
        String signatureContent = ParameterUtils.mapToSignContent(params);
        PrivateKey appPrivateKey = RsaUtils.loadPrivateKey(config.getAppRsaPrivatekey());
        String sign = RsaUtils.signature(appPrivateKey, signatureContent);// 生成签名字符串
        params.put("sign", sign);
        System.out.println("========请求报文是:========");
        System.out.println(JSON.toJSONString(params));
        String str = httpPostJson(url, params, cashoutRecords);
        // 需要把报文进行接续成java对象    抽取出订单编号  和流水号 赋值给商户批次号（也就是流水号）
        ApiBaseResult result = JSON.parseObject(str, ApiBaseResult.class);
        return result;
    }

    private String bankCardIssue(CashOutVO cashOutVO, BigDecimal amount, BizCashoutRecords cashoutRecords) {
        //查询用户信息
        BizMerchantReceiver bizMerchantReceiver = iBizMerchantReceiverService.selectBizMerchantReceiverByUserId(cashoutRecords.getCreateBy());
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String longTome = df.format(System.currentTimeMillis());
        String createCode = createCode(6);
        String request_no = longTome + createCode;
        SimpleDateFormat dsf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = dsf.format(System.currentTimeMillis());
        String url = "https://b.hndbdj.com/api/transfer/transfertobankcard.do";
        Map<String, String> data = new HashMap<String, String>();
        data.put("transfer_corp_id", id);
        data.put("request_no", request_no);
        data.put("name", bizMerchantReceiver.getMerchName());
        data.put("bank_card_no", bizMerchantReceiver.getMerchBankCardno());
        data.put("amount", amount.toString());
        data.put("certificate_type", "1");
        data.put("certificate_no", bizMerchantReceiver.getMerchIdcard());
        data.put("reserved_mobile", bizMerchantReceiver.getMerchBankMobile());
        data.put("notify_url", "http://www.poshb.cn:8083/pos/receiver/payment/callBack");
        data.put("partner_id", partnerId);
        data.put("merchant_id", merchantId);
        data.put("timestamp", timestamp);
        data.put("sign_type", signType);
        String retSign = generateSign(data, signGenerationKey);
        System.out.println("生成的签名为:" + retSign);
        //放入签名后 进行接口请求即可
        data.put("sign", retSign);
        System.out.println("请求报文"+new Gson().toJson(data));
        String str = doPost(url, new Gson().toJson(data));
        System.out.println("返回:" + str);
        // 需要把报文进行接续成java对象    抽取出订单编号  和流水号 赋值给商户批次号（也就是流水号）
        // ReceiverParam result = JSON.parseObject(str, ReceiverParam.class);
        return str;
    }


    public String doPost(String url,String data){
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            //创建请求内容
            String jsonStr = data;
            StringEntity entity = new StringEntity(jsonStr,"utf-8");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }

    ////判断是否追溯
    public final Boolean judgeExtract2(BizMerchant bizMerchant, SynchronizationDataDTO sy) {
        if (bizMerchant.getAscendSwitchSteal().equals("1")&&!"1".equals(sy.getSilenceType())) { // 开关打开
            //判断交易金额是否够偷的最小金额
            String bizAmount = bizMerchant.getAscendMinAmount();
            if (new BigDecimal(sy.getAmnount()).compareTo(new BigDecimal(bizAmount)) > -1) { //大于等于设定的最小偷单金额
                //条件满足 看这单是否偷单
                Boolean b = cyclicUtilization2(sy, bizMerchant);
                return b;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /// 判断这单是否追溯
    private final Boolean cyclicUtilization2(SynchronizationDataDTO sy, BizMerchant bizMerchant) {
        Random random = new Random();
        int suijishu = random.nextInt(100) + 1;
        //查询偷单比例
        String ratioSteal = bizMerchant.getAscendRatioSteal();
        if (Integer.parseInt(ratioSteal) >= suijishu) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 随机字符串
     *
     * @param codeLength
     * @return
     */
    public static String createCode(int codeLength) {
        String code = "";
        for (int i = 0; i < codeLength; i++) {
            code += (int) (Math.random() * 9);
        }
        return code;
    }
    public static String generateSign(Map<String, String> mapData,
                                      String signGenerationKey) {
        try {
            return generateSign(getSortKVStr(mapData), signGenerationKey);
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

    public static String generateSign(String sortKVStr, String signGenerationKey) throws Exception {
        StringBuilder sb = new StringBuilder(sortKVStr);
        sb.append("&key=").append(signGenerationKey);
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] signBytes = digest.digest(sb.toString().getBytes(Charset.forName("utf-8")));
        return Base64.getEncoder().encodeToString(signBytes);
    }

    private static String getSortKVStr(Map<String, String> values) {

        List<String> keys = new ArrayList<String>();
        keys.addAll(values.keySet());

        Collections.sort(keys);

        StringBuffer sb = new StringBuffer();
        int size = keys.size();
        for (int i = 0; i < size; i++) {
            String key = keys.get(i);
            Object value = values.get(key);

            if (value == null) {
                continue;
            }

            if (value instanceof String && "".equals(value)) {
                continue;
            }

            if (sb.length() > 0) {
                sb.append('&');
            }
            sb.append(key).append("=").append(value);
        }

        String sortKVStr = sb.toString();
        System.out.println("参数排序结果为:" + sortKVStr);
        return sortKVStr;
    }
    public BigDecimal queryBalance(Long userId) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(userId);
        Map<String,Object> data=new HashMap<String,Object>();
        data.put("uid",bizAgentidAppkeyDTO.getUid());
        String sign=SaasSignatureUtil.getSignature(bizAgentidAppkeyDTO);
        String requestBodyYe=AESUtil.encrypt(data,bizAgentidAppkeyDTO.getAppsecret());
        String token= bizMerchantReceiverService.acquireAccessToken(bizAgentidAppkeyDTO);
        BigDecimal bigDecimal=new BigDecimal("0.00");
        JSONObject submitBalance=SaasSignatureUtil.submit(bizAgentidAppkeyDTO,"getBalance",sign,requestBodyYe,token);
        if(submitBalance.getString("code").equals("0000")) {
//            String uid = submitBalance.getJSONObject("data").getString("uid");//合作方业务平台 ID
            String balance = submitBalance.getJSONObject("data").getString("balance");//账户余额
            if(com.cykj.common.utils.StringUtils.isNotBlank(balance)){
                bigDecimal=new BigDecimal(balance);
            }
            System.out.println("账户余额  "+balance );
        }
        return bigDecimal;
    }

    @SneakyThrows
    @Override
    public AjaxResult payFeiShunDLG(BizAgentidAppkeyDTO bizAgentidAppkeyDTO ,SubmitGrantDetailDTO submitGrantDetailDTO, BizMicroInfo bizMicroInfoByMerchId,String natchno) {
        AjaxResult ajaxResult = AjaxResult.success("预支付提现");
        // 账户信息
        submitGrantDetailDTO.setEncryptionCardno(0); //不加密卡号
        CashOutVO cashOutVO = microInfoService.getXinLongMerchMicroInfoByUserIdAndAccountType(submitGrantDetailDTO);
        // 提现费用信息
        BizCashoutFee cashoutFee = cashoutFeeService.getXinLongCashoutFeeByType(submitGrantDetailDTO);
        // 开始处理   判断提现金额 是否小于等于账户余额
        String key = cashOutVO.getSecretkey();// 获得key
        String secWalletAmount = cashOutVO.getWalletAmount();// 钱包总金额
        // 获得加密的金额
        String secCashOutAmount = submitGrantDetailDTO.getCashOutAmount();
        // 解密提现数据
        String cashOutAmountStr = DESHelperUtil.decrypt(key, secCashOutAmount);
        BigDecimal cashOutAmount = new BigDecimal(cashOutAmountStr);
        if (submitGrantDetailDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            if (cashOutAmount.compareTo(profitAmount) == 1) { // 大于
                return AjaxResult.error("结算账户余额不足，请重试");
            }
        } else if (submitGrantDetailDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            if (cashOutAmount.compareTo(rewardAmount) == 1) { // 大于
                return AjaxResult.error("奖励账户余额不足，请重试");
            }
        } else if (submitGrantDetailDTO.getAccountType() == 3) { // 流量费账户提现
            String secCoverAmount = cashOutVO.getCoverAmount();// 获得奖励数据
            // 解密数据
            String coverAmountStr = DESHelperUtil.decrypt(key, secCoverAmount);
            // 转换成BigDecimal类型
            BigDecimal coverAmount = new BigDecimal(coverAmountStr);
            if (cashOutAmount.compareTo(coverAmount) == 1) { // 大于
                return AjaxResult.error("服务费账户余额不足，请重试");
            }
        } else if (submitGrantDetailDTO.getAccountType() == 4) { // 服务费账户提现
            String secFlowAmount = cashOutVO.getFlowAmount();// 获得奖励数据
            // 解密数据
            String flowAmountStr = DESHelperUtil.decrypt(key, secFlowAmount);
            // 转换成BigDecimal类型
            BigDecimal flowAmount = new BigDecimal(flowAmountStr);
            if (cashOutAmount.compareTo(flowAmount) == 1) { // 大于
                return AjaxResult.error("流量费账户余额不足，请重试");
            }
        } else {
            return AjaxResult.error("请输入accountType账户类型，1-分润账户 2-补贴账户 3-服务费账户 4-流量费费账户");
        }
        // 提现的扣费金额=服务费+费率   100-2 98
        BigDecimal serviceCharge = cashoutFee.getServiceCharge();//服务费
        BigDecimal rate = cashoutFee.getRewardRate(); //奖励账户费率
        // 需要支付的手续费
        BigDecimal rateFee = cashOutAmount.multiply(rate);
        // 累计需要费用  手续费+服务费
        BigDecimal totalServiceFee = serviceCharge.add(rateFee);
        // 对服务费四舍五入
        String calcTotalServiceFee = BigDecimalUtil.getRoundString(totalServiceFee);
        // 需要支付给用户的费用
        BigDecimal paymentFee = cashOutAmount.subtract(new BigDecimal(calcTotalServiceFee));
        String orderAmt = BigDecimalUtil.getString(paymentFee);//打款金额(元)
        //--------------------------------------------

        // 钱包信息
        BizWallet wallet = walletService.getMyWalletByUserId(submitGrantDetailDTO.getUserId());
        // 钱包金额要做减法
        // 获得总金额
        String walletAmountStr = DESHelperUtil.decrypt(key, secWalletAmount);
        BigDecimal walletAmount = new BigDecimal(walletAmountStr);
        if (submitGrantDetailDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            // 做减法
            profitAmount = profitAmount.subtract(cashOutAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
        } else if (submitGrantDetailDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            // 做减法
            rewardAmount = rewardAmount.subtract(cashOutAmount);
            // 加密
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            wallet.setRewardAmount(rewardAmountMoneyStr);
        }else if (submitGrantDetailDTO.getAccountType() == 3) { // 服务费账户提现
            String secCoverAmount = cashOutVO.getCoverAmount();// 获得服务费数据
            // 解密数据
            String coverAmountStr = DESHelperUtil.decrypt(key, secCoverAmount);
            // 转换成BigDecimal类型
            BigDecimal coverAmount = new BigDecimal(coverAmountStr);
            // 做减法
            coverAmount = coverAmount.subtract(cashOutAmount);
            // 加密
            String coverAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(coverAmount));
            wallet.setCoverAmount(coverAmountMoneyStr);
        }else if (submitGrantDetailDTO.getAccountType() == 4) { // 流量费账户提现
            String secFlowAmount = cashOutVO.getFlowAmount();// 获得流量费数据
            // 解密数据
            String flowAmountStr = DESHelperUtil.decrypt(key, secFlowAmount);
            // 转换成BigDecimal类型
            BigDecimal flowAmount = new BigDecimal(flowAmountStr);
            // 做减法
            flowAmount = flowAmount.subtract(cashOutAmount);
            // 加密
            String flowAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(flowAmount));
            wallet.setFlowAmount(flowAmountMoneyStr);
        }

        // 钱包总额做减法
        walletAmount = walletAmount.subtract(cashOutAmount);
        // 加密钱包总额
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setSecretKey(key);
        try{
            boolean b=walletService.saveOrUpdate(wallet);
            if(!b){
                ajaxResult = AjaxResult.success("钱包扣款失败，请重新提交申请。");
                ajaxResult.put("data", false);
                return ajaxResult;
            }
        }catch (Exception e){
            ajaxResult = AjaxResult.success("钱包扣款失败，请重新提交申请。");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
        BizWallet walletn = walletService.getMyWalletByUserId(submitGrantDetailDTO.getUserId());
        BizMerchantReceiver bizMerchantReceiver = iBizMerchantReceiverService.selectBizMerchantReceiverByUserId(submitGrantDetailDTO.getUserId());
        // 生成支付记录信息
        BizCashoutRecords cashoutRecords = new BizCashoutRecords();
        cashoutRecords.setWalletId(wallet.getWalletId());// 钱包id
        cashoutRecords.setCashoutAmount(cashOutAmount);// 提现金额
        cashoutRecords.setDealAccount(bizMerchantReceiver.getMerchBankCardno());  //提现银行账户
        cashoutRecords.setCashoutType(String.valueOf(submitGrantDetailDTO.getAccountType())); //提现类型 1-结算账户 2-奖励账户
        cashoutRecords.setCashoutStatus("6"); //提现状态  0  预约
        cashoutRecords.setCreateBy(submitGrantDetailDTO.getUserId());//提现人
        cashoutRecords.setVar3(String.valueOf(serviceCharge));// 服务费
        cashoutRecords.setVar4(BigDecimalUtil.getRoundString(rateFee));// 扣费率费用
        cashoutRecords.setVar5(DESHelperUtil.decrypt(walletn.getSecretKey(),walletn.getWalletAmount()));// 账户余额
        cashoutRecordsService.save(cashoutRecords); // 保存

        BigDecimal balnce=this.queryBalanceFS();
        System.out.println("账户余额：==="+balnce);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = df.format(new Date());
        System.out.println("---------------薪龙支付申请时间：" + timestamp + "------------------userId=" + submitGrantDetailDTO.getUserId());
        //开始封装提现数据
        FeiShunSettlement feiShunSettlement =new FeiShunSettlement();
        feiShunSettlement.setBankName(bizMicroInfoByMerchId.getMerchBank());//开户行
        feiShunSettlement.setBankNum(bizMicroInfoByMerchId.getMerchBankCardno());//申请人账号
        feiShunSettlement.setSettleAccount(orderAmt);//结算金额
        feiShunSettlement.setUserName(bizMicroInfoByMerchId.getMerchIdcardName());//申请人名称
        feiShunSettlement.setUserNum(bizMicroInfoByMerchId.getMerchIdcard());//申请人身份证号
        feiShunSettlement.setUserTel(bizMicroInfoByMerchId.getMerchBankMobile());//电话
        feiShunSettlement.setOrderNo(natchno);
        if (cashOutAmount.compareTo(balnce) == 1) { // 大于
            //存入表中挂起状态
            feiShunSettlement.setCreteDate(DateUtils.dateFormatString(new Date()));
            feiShunSettlement.setStatus("10");//挂起状态
            feiShunSettlementMapper.insert(feiShunSettlement);
            // 发消息
            String prepaymentMess = "预约提现成功：提现金额：" + cashOutAmount + "元，手续费" + calcTotalServiceFee + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。";
            System.out.println(prepaymentMess);
            BizMessageRecords prepaymentMessageRecords = new BizMessageRecords();
            prepaymentMessageRecords.setMsgContent(prepaymentMess);// 消息内容
            prepaymentMessageRecords.setMsgType(3); // 消息类型  3
            prepaymentMessageRecords.setReadStatus(0); // 消息未读
            prepaymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(submitGrantDetailDTO.getUserId(), prepaymentMessageRecords);// 发送消息
            cashoutRecords.setVar1(natchno); // 商户批次号修改为企业系统内部订单号
            cashoutRecords.setVar2(natchno); // 订单号修改为请求流水号
            cashoutRecords.setIsRefund("0"); // 订单号修改为请求流水号
            cashoutRecordsService.saveOrUpdate(cashoutRecords); // 重新保存一下
            ajaxResult = AjaxResult.success("支付成功，请关注回调接口。");
            ajaxResult.put("data", true);
            return ajaxResult;
        }else {
            ajaxResult = withdrawFS(feiShunSettlement);//调用派达薪
            String codeDetail = ajaxResult.get("code").toString();
            String messageDetail = (String) ajaxResult.get("msg");
            if (codeDetail.equals("200")) {
                // 发消息
                String prepaymentMess = "预约提现成功：提现金额：" + cashOutAmount + "元，手续费" + calcTotalServiceFee + "元，实际到账金额为："
                        + orderAmt + "元，账户余额为：" + walletAmount + "元,预计T+1到账。";
                System.out.println(prepaymentMess);
                BizMessageRecords prepaymentMessageRecords = new BizMessageRecords();
                prepaymentMessageRecords.setMsgContent(prepaymentMess);// 消息内容
                prepaymentMessageRecords.setMsgType(3); // 消息类型  3
                prepaymentMessageRecords.setReadStatus(0); // 消息未读
                prepaymentMessageRecords.setAdviceType(1); // 业务消息
                webSocketServer.sendInfo(submitGrantDetailDTO.getUserId(), prepaymentMessageRecords);// 发送消息
                cashoutRecords.setVar1(natchno); // 商户批次号修改为企业系统内部订单号
                cashoutRecords.setVar2(natchno); // 订单号修改为请求流水号
                cashoutRecords.setIsRefund("0"); // 订单号修改为请求流水号
                cashoutRecordsService.saveOrUpdate(cashoutRecords); // 重新保存一下
                ajaxResult = AjaxResult.success("支付成功，请关注回调接口。");
                ajaxResult.put("data", true);
                return ajaxResult;
            } else {
                // 回退
                String call_result = prepaymentCallBack(cashoutRecords, messageDetail);
                System.out.println(call_result);
                ajaxResult = AjaxResult.success("支付失败。");
                ajaxResult.put("data", false);
                return ajaxResult;
            }
        }
    }



    public BigDecimal queryBalanceFS(){
        Map map = new HashMap<>();
        map.put("username", FeiShunUtil.username);
        map.put("password", FeiShunUtil.password);
        map.put("remark","company");
        map.put("is",1);
        try {
            String data= FeiShunUtil.doPost(FeiShunUtil.logonUrl,null,JSONObject.toJSONString(map));//派达薪获取token接口
            JSONObject obj = JSONObject.parseObject(data);
            String code = obj.getString("code");
            String accessToken = obj.getString("data");
            JSONObject accessTokenObj = JSONObject.parseObject(accessToken);
            String token=accessTokenObj.getString("access_token");
            JSONObject balanceData= FeiShunUtil.send(FeiShunUtil.balanceUrl,token,null);//查询余额接口
            String balanceCode = balanceData.getString("code");
            BigDecimal balance=new BigDecimal("0");
            if("200".equals(balanceCode)){
                balance=new BigDecimal(balanceData.getString("data"));
            }
            return balance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 派达薪支付接口
     * @return
     */
    public AjaxResult withdrawFS(FeiShunSettlement feiShunSettlement){
        Map map = new HashMap<>();
        map.put("username", FeiShunUtil.username);
        map.put("password", FeiShunUtil.password);
        map.put("remark","company");
        map.put("is",1);
        try {
            String data= FeiShunUtil.doPost(FeiShunUtil.logonUrl,null,JSONObject.toJSONString(map));//派达薪获取token接口
            JSONObject obj = JSONObject.parseObject(data);
            String code = obj.getString("code");
            String accessToken = obj.getString("data");
            JSONObject accessTokenObj = JSONObject.parseObject(accessToken);
            String token=accessTokenObj.getString("access_token");
            String msg = obj.getString("msg");
            if("200".equals(code)){//判断获取token结果
                map.clear();
                //封装任务申请参数
                map.put("taskId", FeiShunUtil.taskId);//任务id
                List settleUserVos=new ArrayList();//申请人集合
                Map listMap = new HashMap<>();
                listMap.put("bankName", feiShunSettlement.getBankName());//申请人开户银行
                listMap.put("bankNum", feiShunSettlement.getBankNum());//申请人银行账户
                listMap.put("settleAccount", feiShunSettlement.getSettleAccount());//金额(元)
                listMap.put("userName", feiShunSettlement.getUserName());//申请人名称
                listMap.put("userNum", feiShunSettlement.getUserNum());//申请人身份证号
                listMap.put("userTel", feiShunSettlement.getUserTel());//申请人手机号
                listMap.put("bankSubName", feiShunSettlement.getBankSubName());//申请人开户支行 非必填
                listMap.put("remark", feiShunSettlement.getRemark());//透传参数  非必填
                settleUserVos.add(listMap);
                map.put("settleUserVos",settleUserVos);
                JSONObject resData= FeiShunUtil.send(FeiShunUtil.applyUrl,token,JSONObject.toJSONString(map));//任务申请接口
                String taskCode = resData.getString("code");
                String taskMsg = resData.getString("msg");
                if("200".equals(taskCode)){
                    JSONObject taskObj= JSONObject.parseObject(resData.getString("data"));
                    String cpayCount = taskObj.getString("cpayCount");//需打款金额
                    String settlementId = taskObj.getString("settlementId");//任务结算ID
                    JSONArray userVos=taskObj.getJSONArray("userVos");
                    for(Object m:userVos){
                        Map mapVo= (Map) m;
                        feiShunSettlement.setTaskUserId((String) mapVo.get("taskUserId"));
                    }
                    feiShunSettlement.setCpayCount(cpayCount);
                    feiShunSettlement.setCreteDate(DateUtils.dateFormatString(new Date()));
                    //开始调用发起结算接口
                    map.clear();
                    map.put("settlementId",settlementId);//任务结算 id
                    JSONObject settData= FeiShunUtil.send(FeiShunUtil.initiateSettUrl,token,JSONObject.toJSONString(map));//发起结算接口
                    String settCode = settData.getString("code");
                    String settMsg = resData.getString("msg");
                    if("200".equals(settCode)){
                        //存储申请的结算信息
                        feiShunSettlement.setTaskId(FeiShunUtil.taskId);
                        feiShunSettlement.setStatus("1");
                        feiShunSettlement.setBankSubName("");
                        feiShunSettlement.setErrorMessage("");
                        feiShunSettlement.setRemark("");
                        feiShunSettlement.setSettlementId(settlementId);

                        feiShunSettlementMapper.insert(feiShunSettlement);
                        return AjaxResult.success("提现流程已发起，请等待提现结果");
                    }else{
                        return AjaxResult.error("发起结算失败，原因："+settMsg);
                    }
                }else{
                    return AjaxResult.error("申请任务失败，原因："+taskMsg);
                }
            }else{
                return AjaxResult.error("获取token失败，原因："+msg);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @SneakyThrows
    @Override
    public AjaxResult payYLG(SubmitGrantDetailDTO submitGrantDetailDTO, BizMicroInfo bizMicroInfoByMerchId,String natchno) {
        AjaxResult ajaxResult = AjaxResult.success("预支付提现");
        // 账户信息
        submitGrantDetailDTO.setEncryptionCardno(0); //不加密卡号
        CashOutVO cashOutVO = microInfoService.getXinLongMerchMicroInfoByUserIdAndAccountType1(submitGrantDetailDTO);
        // 提现费用信息
        BizCashoutFee cashoutFee = cashoutFeeService.getXinLongCashoutFeeByType(submitGrantDetailDTO);
        // 开始处理   判断提现金额 是否小于等于账户余额
        String key = cashOutVO.getSecretkey();// 获得key
        String secWalletAmount = cashOutVO.getWalletAmount();// 钱包总金额
        // 获得加密的金额
        String secCashOutAmount = submitGrantDetailDTO.getCashOutAmount();
        // 解密提现数据

        // ---------------------------------这里做测试用的 记得改回来-----------------------------------

        String cashOutAmountStr = DESHelperUtil.decrypt(key, secCashOutAmount);
        BigDecimal cashOutAmount = new BigDecimal(cashOutAmountStr);
        if (submitGrantDetailDTO.getAccountType() == 1) {// 结算账户提现
            String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
            // 解密数据
            String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
            // 转换成BigDecimal类型
            BigDecimal profitAmount = new BigDecimal(profitAmountStr);
            if (cashOutAmount.compareTo(profitAmount) == 1) { // 大于
                return AjaxResult.error("结算账户余额不足，请重试");
            }
        } else if (submitGrantDetailDTO.getAccountType() == 2) { // 奖励账户提现
            String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
            // 解密数据
            String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
            // 转换成BigDecimal类型
            BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
            if (cashOutAmount.compareTo(rewardAmount) == 1) { // 大于
                return AjaxResult.error("奖励账户余额不足，请重试");
            }
        } else {
            return AjaxResult.error("请输入accountType账户类型，1-结算账户 2-奖励账户");
        }
        // 提现的扣费金额=服务费+费率   100-2 98
        BigDecimal serviceCharge = cashoutFee.getServiceCharge();//服务费
        //BigDecimal rate = cashoutFee.getRate();//结算账户费率
        //if(submitGrantDetailDTO.getAccountType() == 2){
        BigDecimal rate = cashoutFee.getRewardRate(); //奖励账户费率
        //}
        // 需要支付的手续费
        BigDecimal rateFee = cashOutAmount.multiply(rate);
        // 累计需要费用  手续费+服务费
        BigDecimal totalServiceFee = serviceCharge.add(rateFee);
        // 对服务费四舍五入
        String calcTotalServiceFee = BigDecimalUtil.getRoundString(totalServiceFee);
        // 需要支付给用户的费用
        BigDecimal paymentFee = cashOutAmount.subtract(new BigDecimal(calcTotalServiceFee));
        String orderAmt = BigDecimalUtil.getString(paymentFee);//打款金额(元)
        //--------------------------------------------

        // 钱包信息
        BizWallet wallet = walletService.getMyWalletByUserId(submitGrantDetailDTO.getUserId());
        // 钱包金额要做减法
        // 获得总金额
        String walletAmountStr = DESHelperUtil.decrypt(key, secWalletAmount);
        BigDecimal walletAmount = new BigDecimal(walletAmountStr);
//        BigDecimal balnce=this.queryBalance();
//        System.out.println("账户余额：==="+balnce);
//        if (cashOutAmount.compareTo(balnce) == 1) { // 大于
//            return AjaxResult.error("账户余额不足，请重试");
//        }
        String secProfitAmount = cashOutVO.getProfitAmount();//获得结算账户余额
        // 解密数据
        String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
        // 转换成BigDecimal类型
        BigDecimal profitAmount = new BigDecimal(profitAmountStr);


        String secRewardAmount = cashOutVO.getRewardAmount();// 获得奖励数据
        // 解密数据
        String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
        // 转换成BigDecimal类型
        BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);

        if (submitGrantDetailDTO.getAccountType() == 1) {// 结算账户提现
            // 做减法
            profitAmount = profitAmount.subtract(cashOutAmount);
            // 加密
            String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
            wallet.setProfitAmount(profitAmountMoneyStr);
        } else if (submitGrantDetailDTO.getAccountType() == 2) { // 奖励账户提现

            // 做减法
            rewardAmount = rewardAmount.subtract(cashOutAmount);
            // 加密
            String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
            wallet.setRewardAmount(rewardAmountMoneyStr);
        }

        // 钱包总额做减法
        walletAmount = walletAmount.subtract(cashOutAmount);
        // 加密钱包总额
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        walletService.saveOrUpdate(wallet);
        boolean b = walletService.saveOrUpdate(wallet);
        if (!b) {
            ajaxResult = AjaxResult.success("支付失败。");
            ajaxResult.put("data", false);
            return ajaxResult;
        }
        BizWallet walletn = walletService.getMyWalletByUserId(submitGrantDetailDTO.getUserId());
        BizMerchantReceiver bizMerchantReceiver = iBizMerchantReceiverService.selectBizMerchantReceiverByUserId(submitGrantDetailDTO.getUserId());
        // 生成支付记录信息
        BizCashoutRecords cashoutRecords = new BizCashoutRecords();
        cashoutRecords.setWalletId(wallet.getWalletId());// 钱包id
        cashoutRecords.setCashoutAmount(cashOutAmount);// 提现金额
        cashoutRecords.setDealAccount(bizMerchantReceiver.getMerchBankCardno());  //提现银行账户
        // cashoutRecords.setDealBank(cashOutVO.getMerchBank());  //提现所属银行
        cashoutRecords.setCashoutType(String.valueOf(submitGrantDetailDTO.getAccountType())); //提现类型 1-结算账户 2-奖励账户
        cashoutRecords.setCashoutStatus("6"); //提现状态  0  预约
        cashoutRecords.setCreateBy(submitGrantDetailDTO.getUserId());//提现人
        /*cashoutRecords.setVar1(custBatchNo); // 商户批次号
        cashoutRecords.setVar2(orderNo); //订单号*/
        cashoutRecords.setVar3(String.valueOf(serviceCharge));// 服务费
        cashoutRecords.setVar4(BigDecimalUtil.getRoundString(rateFee));// 扣费率费用
        cashoutRecords.setVar5(DESHelperUtil.decrypt(walletn.getWalletAmount(), walletn.getSecretKey()));// 账户余额
        cashoutRecordsService.save(cashoutRecords); // 保存

        // ylg 提现
        String withDrawalResult = withDrawalYlg(bizMicroInfoByMerchId, orderAmt, natchno);
        System.out.println(bizMicroInfoByMerchId.getMerchIdcardName() + "提现返回参数" + JSONObject.toJSONString(withDrawalResult));
        JSONObject result = JSONObject.parseObject(withDrawalResult);
        if (result.get("code").equals("0000")) {
            String ylgData = result.get("result").toString();
            JSONObject ylgOrderData = JSONObject.parseObject(ylgData);
            // 发消息
            String prepaymentMess = "预约提现成功：提现金额：" + cashOutAmount + "元，手续费" + calcTotalServiceFee + "元，实际到账金额为："
                    + orderAmt + "元，账户余额为：" + walletAmount + "元。";
            System.out.println(prepaymentMess);
            BizMessageRecords prepaymentMessageRecords = new BizMessageRecords();
            prepaymentMessageRecords.setMsgContent(prepaymentMess);// 消息内容
            prepaymentMessageRecords.setMsgType(3); // 消息类型  3
            prepaymentMessageRecords.setReadStatus(0); // 消息未读
            prepaymentMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(submitGrantDetailDTO.getUserId(), prepaymentMessageRecords);// 发送消息
            /*// 获得请求流水号 reqNo
            String reqNo = object.getString("deal_no");
            // 获得企业系统内部订单号 outOrderNo
            String outOrderNo = object.getString("deal_no");*/
            cashoutRecords.setVar1(natchno); // 商户批次号修改为企业系统内部订单号
            cashoutRecords.setVar2(natchno); // 订单号修改为请求流水号
            cashoutRecords.setIsRefund("0");
            cashoutRecordsService.saveOrUpdate(cashoutRecords); // 重新保存一下
            BizYlgWithdrawalPoll bizYlgWithdrawalPoll = new BizYlgWithdrawalPoll();
            bizYlgWithdrawalPoll.setName(bizMicroInfoByMerchId.getMerchIdcardName());
            bizYlgWithdrawalPoll.setAmount(Double.parseDouble(orderAmt));
            bizYlgWithdrawalPoll.setOrderNo(natchno);
            bizYlgWithdrawalPoll.setCreateTime(new Date());
            bizYlgWithdrawalPoll.setUserId(submitGrantDetailDTO.getUserId());
            bizYlgWithdrawalPoll.setYlgOrderNo(ylgOrderData.get("data").toString());
            bizWalletMapper.saveBizYlgWithdrawalPoll(bizYlgWithdrawalPoll);
            ajaxResult = AjaxResult.success("支付成功，请关注回调接口。");
            ajaxResult.put("data", true);
            return ajaxResult;
        } else {
            // 回退
            String call_result = prepaymentCallBack(cashoutRecords, result.get("content").toString());
            System.out.println(call_result);
            ajaxResult = AjaxResult.success("支付失败。" );
            ajaxResult.put("data", false);
            return ajaxResult;
        }
    }

    private String withDrawalYlg(BizMicroInfo bizMicroInfo,String orderAmount,String natchno) {
        JSONObject reqData = new JSONObject();
        reqData.put("reName",bizMicroInfo.getMerchIdcardName());//收款姓名
        reqData.put("reIdNo",bizMicroInfo.getMerchIdcard());
        reqData.put("rePhone",bizMicroInfo.getMerchBankMobile());
        reqData.put("reBankCardNo",bizMicroInfo.getMerchBankCardno());
        String bankName = obtainBank(bizMicroInfo.getMerchBankCardno());
        if(bankName == null){
            JSONObject res = new JSONObject();
            res.put("code","0055");
            res.put("content","银行卡解析失败");
            return res.toString();
        }
        reqData.put("reBankName",bankName);
        reqData.put("trRemark",bizMicroInfo.getMerchIdcardName()+"申请提现"+orderAmount+"元");
        reqData.put("orderNo",natchno);
        reqData.put("trAmount",new BigDecimal(orderAmount));
        List<String> params = new ArrayList<String>();
        params.add(reqData.toJSONString());
        Console.log(bizMicroInfo.getMerchIdcardName()+"提现请求参数"+params);
        return YlgUtil.YLG_POST(PosPCommonParamConfig.getPayOrderBatch(),params.toString());
    }



    public String obtainBank(String cardNo){
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json";
        String parm = "cardNo="+cardNo+"&cardBinCheck=true";
        HttpUtil httpUtil = new HttpUtil();
        String result = httpUtil.doGet(url, parm);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String bankName = "未知银行";
        if(jsonObject.getString("validated").equals("true")){
            System.out.println(jsonObject.getString("bank"));
            bankName = bizWalletMapper.getBankNameByBankCode(jsonObject.getString("bank"));
            System.out.println(bankName);
        }
        return bankName;
    }


    @Override
    public List<BizYlgWithdrawalPoll> getYlgWithdrawalList(){
        return bizWalletMapper.getYlgWithdrawalList();
    }

    @Override
    public void queryYlgWithdrawalStatus(BizYlgWithdrawalPoll bizYlgWith){
        JSONObject reqData = new JSONObject();
        reqData.put("orderSn",bizYlgWith.getYlgOrderNo());
        System.out.println(bizYlgWith.getName()+"订单号:"+bizYlgWith.getOrderNo()+"查询代付结果请求"+JSONObject.toJSONString(reqData));
        String result = YlgUtil.YLG_POST(PosPCommonParamConfig.getQueryOrderInfo(),reqData.toJSONString());
        System.out.println(bizYlgWith.getName()+"订单号:"+bizYlgWith.getOrderNo()+"查询代付结果结果"+JSONObject.toJSONString(result));
        JSONObject res = JSONObject.parseObject(result);
        if(res.get("code").equals("0000")){
            String resultContent = res.get("result").toString();
            JSONObject resContent = JSONObject.parseObject(resultContent);
            BizCashoutRecords cashoutRecords = cashoutRecordsService.getCashoutRecordsByCustOrderNo(bizYlgWith.getOrderNo());
            String data = resContent.get("data").toString();
            JSONObject resData = JSONObject.parseObject(data);
            if(resData.get("sendFlag").toString().equals("2")){ //成功
                if(cashoutRecords!=null){
                    // 发消息
                    String var3 = cashoutRecords.getVar3();
                    String var4 = cashoutRecords.getVar4();
                    BigDecimal serviceFee = new BigDecimal(var3);
                    BigDecimal rateFee = new BigDecimal(var4);
                    BigDecimal totalServiceFee = serviceFee.add(rateFee);
                    BigDecimal orderAmt = cashoutRecords.getCashoutAmount().subtract(totalServiceFee);
                    String walletAmount = cashoutRecords.getVar5();
                    String paymentMess = "您的提现已成功到账，提现金额：" + cashoutRecords.getCashoutAmount() + "元，实际到账金额为："
                            + orderAmt + "元，账户余额为：" + walletAmount + "元。提现到" + cashoutRecords.getDealBank() +
                            ",提现订单号是：" + cashoutRecords.getVar2();
                    System.out.println(paymentMess);
                    BizMessageRecords paymentMessageRecords = new BizMessageRecords();
                    paymentMessageRecords.setMsgContent(paymentMess);// 消息内容
                    paymentMessageRecords.setMsgType(4); // 消息类型  4
                    paymentMessageRecords.setReadStatus(0); // 消息未读
                    paymentMessageRecords.setAdviceType(1); // 业务消息
                    webSocketServer.sendInfo(bizYlgWith.getUserId(), paymentMessageRecords);// 发送消息
                    // 生账单
                    BizMerchBill merchBill = new BizMerchBill();
                    BizMerchant merchant = merchantService.getMerchantByUserId(bizYlgWith.getUserId()); //商户信息
                    merchBill.setMerchId(merchant.getMerchId());// 商户id
                    merchBill.setMerchName(merchant.getMerchName());// 商户名称
                    merchBill.setBillType("4");// 款项类型 1-返现 2-分润 3-奖励 4-提现 5-押金
                    Date date = cashoutRecords.getCreateTime();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    merchBill.setBillDate(sdf.format(date)); //账单日期  与提现日期一致
                    merchBill.setCashoutRecordsId(cashoutRecords.getCashoutId());// 提现id
                    merchBill.setAmount(cashoutRecords.getCashoutAmount().negate()); // 提现存的是负值
                    merchBillService.save(merchBill); // 存账单数据
                    // 提现记录  更新状态为 1
                    cashoutRecords.setCashoutStatus("1");
                    cashoutRecords.setVar1(bizYlgWith.getOrderNo());
                    cashoutRecords.setMsgId(paymentMessageRecords.getMsgId()); // 存储记录中对应的消息id
                    cashoutRecordsService.saveOrUpdate(cashoutRecords);
                }
            }else if(resData.get("sendFlag").toString().equals("3")){
                if(cashoutRecords!=null) {
                    if (cashoutRecords.getIsRefund().equals("0")) {
                        BizWallet wallet = walletService.getMyWalletByUserId(bizYlgWith.getUserId());
                        String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
                        String secRewardAmount = wallet.getRewardAmount();// 获得奖励数据
                        String key = wallet.getSecretKey();// 获得key
                        // 解密数据
                        String profitAmountStr = DESHelperUtil.decrypt(key, secProfitAmount);
                        String rewardAmountStr = DESHelperUtil.decrypt(key, secRewardAmount);
                        // 转换成BigDecimal类型
                        BigDecimal profitAmount = new BigDecimal(profitAmountStr);
                        BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
                        // 预支付出去的金额为
                        BigDecimal paymentMoney = cashoutRecords.getCashoutAmount();
                        // 根据cashout_type  提现类型 1-结算账户 2-奖励账户
                        String cashoutType = cashoutRecords.getCashoutType();
                        if ("1".equals(cashoutType)) {//1-结算账户
                            profitAmount = profitAmount.add(paymentMoney);
                        } else if ("2".equals(cashoutType)) {//2-奖励账户
                            rewardAmount = rewardAmount.add(paymentMoney);
                        }
                        BigDecimal walletAmount = profitAmount.add(rewardAmount);
                        // 加密
                        String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
                        String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
                        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
                        wallet.setProfitAmount(profitAmountMoneyStr);
                        wallet.setRewardAmount(rewardAmountMoneyStr);
                        wallet.setWalletAmount(walletAmountMoneyStr);
                        wallet.setSecretKey(key);
                        // 保存钱包信息
                        walletService.saveOrUpdate(wallet);
                        // 发消息
                        String paymentFailMess = "您的提现失败，提现金额" + cashoutRecords.getCashoutAmount() + "元已经返回您的余额请注意查收，提现订单号" +
                                cashoutRecords.getVar2() + "，失败原因：交易失败";
                        System.out.println(paymentFailMess);
                        BizMessageRecords paymentFailMessageRecords = new BizMessageRecords();
                        paymentFailMessageRecords.setMsgContent(paymentFailMess);// 消息内容
                        paymentFailMessageRecords.setMsgType(5); // 消息类型  5
                        paymentFailMessageRecords.setReadStatus(0); // 消息未读
                        paymentFailMessageRecords.setAdviceType(1); // 业务消息
                        webSocketServer.sendInfo(bizYlgWith.getUserId(), paymentFailMessageRecords);// 发送消息
                        // 提现记录  更新状态为 0  失败
                        cashoutRecords.setCashoutStatus("0");
                        cashoutRecords.setMsgId(paymentFailMessageRecords.getMsgId()); // 存储记录中对应的消息id
                        cashoutRecords.setErrorMsg("---错误信息：");// 存储失败原因
                        cashoutRecords.setErrorMsg("1");
                        cashoutRecordsService.saveOrUpdate(cashoutRecords);
                    }
                }
            }
            bizYlgWith.setStatus(resData.get("sendFlag").toString());
            bizWalletMapper.updateOrderStatus(bizYlgWith);
        }else{
            Console.log(bizYlgWith.getOrderNo()+"订单查询接口调用失败"+res.get("content"));
        }
    }



    public Map<String, Object> hyqWithdrawal(String natchno,String orderAmt,BizMicroInfo bizMicroInfoByMerchId){
        /******************调用接口*************************/
        BatchPayment req = new BatchPayment();
        req.setBatchNo(natchno);
        //获取数据库 enable为2 的可用数据
        String  batchNo = cashoutRecordsService.getPathNoEnableLzf();
        logger.info("新代付提现   batchNo:  "+batchNo);
        req.setPathNo(batchNo);
        req.setTotalAmount(orderAmt);
        req.setTotalNum("1");
        List<BatchPaymentList> list = new ArrayList<>();
        BatchPaymentList order = new BatchPaymentList();
        order.setOrderId(IdGen.uuid());
        order.setCardId(bizMicroInfoByMerchId.getMerchIdcard());
        order.setCardNo(bizMicroInfoByMerchId.getMerchBankCardno());
        order.setPayAmount(orderAmt);
        order.setPhoneNo(bizMicroInfoByMerchId.getMerchBankMobile());
        order.setRealName(bizMicroInfoByMerchId.getMerchIdcardName());
        list.add(order);
        req.setPayInfos(list);
        BizBehalfPayment bizBehalfPayment = bizMicroInfoService.getBehalfPaymentByCode("860141210603821");
        Map<String, Object> hqyResultMap = HqyApiUtilsV2.callHqyMerApi(UUID.randomUUID().toString(), HqyMerFunctionEnumsV2.BATCH_PAYMENT.getCode(), req,bizBehalfPayment);
        return hqyResultMap;
    }

}
